React JS根据用户输入显示月份

时间:2019-02-08 21:27:49

标签: javascript html reactjs react-redux frontend

我正在尝试根据用户输入显示月份名称。我有一个名为Constants js的文件,它定义了我的month数组。     情况1:     当用户单击“提交”按钮时在文本字段中输入4时,应显示4月     情况2:     当用户输入33月份号时,应显示“无效月份号”

Home JS file
<code>
import React, { Component }  from 'react';
import constants from './Constants';

class Home extends React.Component{
    constructor(props)
    {
        super(props);
        this.state ={
        value : ''
        }
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick = (event) => 
    {
        this.setState({value: event.target.value})
    }

  render()
  {
    let newvalue = this.value;
     let latestvalue = constants.MONTHS[newvalue] == null ? 'invalid month' : constants.MONTHS[newvalue]  ; 
    return(
        <div className='home'>
        <h1>Welcome to my portfolio website</h1>
        Enter Month number <input type="text" value={this.state.value}/> 
        <button type="button" onSubmit={this.handleClick()}> </button>
        <p> Feel free to browse around and learn more about me.</p>
        Month is {latestvalue}
      </div>

     );
  }

}

export default Home;
</code>

Constants JS file

<code>

const constants = {

        MONTHS: ['','Jan','Feb','Mar','April','May','June','July']

}

export default constants;
</code>

It should display month or invalid month

我收到此错误“ TypeError:无法读取未定义的属性'target'”

1 个答案:

答案 0 :(得分:1)

import React, { Component }  from 'react';
import constants from './Constants';

class Home extends React.Component{
    constructor(props)
    {
        super(props);
        this.state ={
        value : 0,
        month: constants.MONTHS[0]
        }
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick = (event) => 
    {
        this.setState({value: event.target.value})
    }
    handleSubmit = () => {
        const month = constants.MONTHS[this.state.value] || 'invalid month'
        this.setState({
        month: month
       })
    }

  render()
  {

    return(
        <div className='home'>
        <h1>Welcome to my portfolio website</h1>
        Enter Month number <input type="text" onChange={this.handleClick} value={this.state.value}/> 
        <button type="button" onSubmit={this.handleSubmit}> </button>
        <p> Feel free to browse around and learn more about me.</p>
        Month is {this.state.month}
      </div>

     );
  }

}

export default Home;