React根据用户输入显示月份功能报错:TypeError: Cannot read property 'target' of undefined
Hey there! Let's fix those issues in your React code step by step. I can see exactly what's causing that TypeError and a few other small problems getting in the way of your month lookup feature.
First, the root cause of the TypeError: Cannot read property 'target' of undefined
You’re calling this.handleClick() directly in the button’s onSubmit prop. Those parentheses make the function run immediately when the component renders (not when the button is clicked!), and since you’re not passing an event argument manually, event becomes undefined. On top of that, onSubmit is meant for <form> elements—use onClick for buttons instead, and pass the function reference without parentheses.
Other issues blocking your feature
- Your input field doesn’t have an
onChangehandler, so typing in it won’t update your component’s state. Right now, the input’s value is bound to state but there’s no way to update state when the user types. - You’re trying to access
this.valueinstead ofthis.state.valueto get the current input value—this.valuedoesn’t exist on your component! - Your month validation logic doesn’t properly check if the input is a valid number within the range of your
MONTHSarray (1 to 7, since your array starts with an empty string at index 0).
Fixed Home.js Code
import React, { Component } from 'react'; import constants from './Constants'; class Home extends React.Component { constructor(props) { super(props); this.state = { value: '' }; } // Update state whenever the user types in the input handleInputChange = (event) => { this.setState({ value: event.target.value }); }; // Trigger month lookup when the button is clicked handleClick = () => { // We don't need the event here—we'll pull the value directly from state in render }; render() { const monthNum = parseInt(this.state.value, 10); let monthName; // Validate input: check if it's a number, and within 1-7 (matching your MONTHS array) if (isNaN(monthNum) || monthNum < 1 || monthNum >= constants.MONTHS.length) { monthName = 'invalid month number'; } else { monthName = constants.MONTHS[monthNum]; } return ( <div className='home'> <h1>Welcome to my portfolio website</h1> Enter Month number {/* Add onChange to sync input with state */} <input type="text" value={this.state.value} onChange={this.handleInputChange} /> {/* Use onClick with function reference (no parentheses!) */} <button type="button" onClick={this.handleClick}> Get Month Name </button> <p> Feel free to browse around and learn more about me.</p> Month is {monthName} </div> ); } } export default Home;
Key Changes Explained
- Input Sync: The
handleInputChangefunction updates the component’s state whenever the user types, so the input value and state stay in sync. - Button Handler: Changed to
onClick={this.handleClick}(no parentheses!) so the function runs only when the button is clicked. We also removed theeventparameter fromhandleClicksince we’re using state directly. - Proper Validation: Checks if the input is a valid number, and if it falls within the 1-7 range (matching your
MONTHSarray). This handles non-numeric input, numbers too low/high, and empty input. - State Access: Uses
this.state.valueinstead of the non-existentthis.valueto get the current input value.
Your Constants.js is Good to Go!
Your MONTHS array is set up correctly (empty string at index 0, so index 4 maps to April as expected). No changes needed there.
内容的提问来源于stack exchange,提问作者Rohan

