简体   繁体   中英

select box in reactjs not working

I have a form with a select box that gets data from the server and post it to the same server. I'm using select box from ant design .

But that part that handles changes handleChange() is not working and give me this error :

Cannot read property 'value' of undefined


This is my code:

let optionData = [];

class ContentCountries extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      value: 'Select',
      jsonData: 0
    };
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }
  handleSubmit(event) {
    event.preventDefault();
    var data = {
      name: this.state.value
    }
   console.log(data);
    /*$.ajax({
      type: 'POST',
      url: 'https://google.com',
      data: data
    })*/
  }
  componentDidMount(){
    //ajax request
    /*$.ajax({
      type: 'GET',
      url: 'https://google.com',
      succes: function(data){
        optionData = data;
      }
    })*/
    //static example
    optionData.push('Bangalore');
    optionData.push('Pune');
    this.setState({jsonData: 1});//change the status so the select tag will get the new values(render will happen)
  }
  render() {
    var optionsTag = <Option value="">Select City</Option>  
   if(optionData.length){
     optionsTag = optionData.map((data,index) => {
                          return <Option value={data} key={index}>{data}</Option>
                          })
   }

    return (
   <form onSubmit={false}>
        <label>
          Please select city:
          <Select value={this.state.value} onChange={this.handleChange.bind(this)}>
            { optionsTag}
          </Select>
        </label>
        <input type="button" onClick={this.handleSubmit.bind(this)} value="Submit" />
      </form>
    )
  }
}

EDITED: Sorry, as you said, it is Ant Design . However, it is almost the same with your handleChange function. Because it takes the value as the argument, not the event. So that there is no target property inside passed argument.

 handleChange(val) { this.setState({value: val}); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM