简体   繁体   中英

TypeError: event.target on React Select input control

Trying to change state on Change using a React Select node module package, if its a regular text input it works but can't quite get this to work, returns "TypeError: event.target is undefined".

Only putting in the code that matters, not full page.


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "15",
      options: [
        { label: "Sup", value: "18" },
        { label: "Sup", value: "18" },
        { label: "Sup", value: "18" },
        { label: "Sup", value: "18" }
      ]
    };

    this.stateChange = this.stateChange.bind(this);
  }

  stateChange = event => {
    console.log(event.target.value);
    // this.setState({ value: event.target.value });
  };

  render() {
    const Home = () => {
      return (
        <Provider store={store}>
              <div className="categories">

                <Select
                  options={this.state.options}
                  onChange={this.stateChange}
                />

              </div>

If you're using the react-select library, it looks like the Select component's onChange prop will actually just give you the selected item rather than an event:

stateChange = selectedOption => {
  console.log(selectedOption);
  this.setState({ value: selectedOption });
};

Try this:

stateChange = selectedOption => {
    console.log(`Option selected:`, selectedOption);
    this.setState({ value: selectedOption });
    // with React-Select, selectedOption is a value of option, not an event
};

React select onChange gives you the value directly, instead of the event , so you can simply use,

stateChange = value => {
  console.log(value);
  this.setState({ value: value });
};

React select docs

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