【问题标题】:React: saving selected options into state反应:将选定的选项保存到状态
【发布时间】:2019-08-27 14:54:21
【问题描述】:

我正在尝试将我的选择框的选定选项保存在状态中。在我的框中选择某些内容时出现错误...看起来“事件”未定义,我看不出为什么会出现这种情况。

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

【问题讨论】:

标签: reactjs react-select


【解决方案1】:

这是因为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】:

    这里有 2 个问题。

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

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

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

    Demo

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2016-06-06
      • 2022-01-13
      • 2019-04-16
      • 2021-07-03
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多