You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React根据用户输入显示月份功能报错:TypeError: Cannot read property 'target' of undefined

Fixing Your React Month Lookup Feature

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

  1. Your input field doesn’t have an onChange handler, 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.
  2. You’re trying to access this.value instead of this.state.value to get the current input value—this.value doesn’t exist on your component!
  3. Your month validation logic doesn’t properly check if the input is a valid number within the range of your MONTHS array (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 handleInputChange function 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 the event parameter from handleClick since 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 MONTHS array). This handles non-numeric input, numbers too low/high, and empty input.
  • State Access: Uses this.state.value instead of the non-existent this.value to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:32:43