React:将选定的选项保存到状态

React: saving selected options into state

我正在尝试将我的 select 框的 selected 选项保存在状态中。当 select 在我的框中输入某些内容时出现错误...看起来 "event" 未定义,我看不出为什么会出现这种情况。

import React, { Component } from 'react'
import Select from 'react-select'

class SwitchList extends React.Component{
  constructor(){ 
    super()
    this.state = {
      switches: [],
      selectedOption: []
    }
  }
  handleChange(event){
    this.setState({selectedOption: event.target.value })
  }
  render() {
    return(
      <Select
        value={this.state.selectedOption}
        options={this.state.switches}
        onChange={this.handleChange}
      />
    )
  }
}
> Uncaught TypeError: Cannot read property 'value' of undefined

发生这种情况是因为 react-select 库中 onChange 回调的第一个参数不是 React 的 SyntheticEvent 的实例。第一个参数 - 是一个选项,已被选中。此外,您需要将 handleChange 函数绑定到 this 或使用箭头函数。这是一个正确的代码:

constructor(){ 
    super()
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      switches: [],
      selectedOption: []
    }
  }

...
  handleChange(option){
    this.setState({selectedOption: option.value })
  }
...

还有一个建议。如果您对参数或变量的类型或值没有信心,请使用 console.log 或浏览器调试工具。

这里有 2 个问题。

首先,您需要将 this 绑定到 handleChange 函数。为此,您可以使用箭头功能,

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

其次,react-select直接给你格式{value: "", label: ""}的选项,你可以直接在状态中设置。

Demo