【问题标题】:react-select onChange not working after change optionsreact-select onChange 在更改选项后不起作用
【发布时间】:2020-06-18 13:47:12
【问题描述】:

我有一个使用 react-select 的组件,我从 props 中获取选项, 在 selct 选项上,我想用其他选项重新呈现选择 - 它有效,但未触发 onChange。

import Select from 'react-select';

onChange(option){ 
   dispatch(updateOptions());
}

render(){
  return 
    <Select
      options={this.props.options}
      onChange={this.onChange}
      value={this.state.text}
      menuIsOpen
    />
} 

【问题讨论】:

  • 你在构造函数中bind 操作了吗?
  • 您的 Select 组件来自哪里?快速查看库的文档可能会帮助我们解决问题
  • 这里需要更清楚,“在选择选项上我想用其他选项重新呈现选择”是什么意思,你想为Select 组件提供一个新的选项数组吗? updateOptions 动作创建者如何工作?您的减速机是否正确处理机箱?这里没有足够的代码来做假设,codeandbox可以帮助我们更好地理解问题。

标签: reactjs react-select


【解决方案1】:

请查看this example,我创建了两个组件,一个是Functional Component,另一个是Class Component

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我是一个例子,它有效吗? 让我们在你的代码上试试吧

    import React, { Component } from 'react';
    import Select from 'react-select';
    
    
    export default class FixedOptions extends Component {
      state = {
        value: {},
      };
    
      constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
      }
    
      onChange(value) {
        console.log(value)
        this.setState({ value: value });
      }
    
      render() {
        return (
          <Select
            value={this.state.value}
            onChange={this.onChange}
            options={[{a: 1, b: 2}, {a: 2, b: 3}]}
          />
        );
      }
    }
    

    【讨论】:

    • 在 onChange 我想更新选项,而不是值。
    • onChange 事件触发后,您可以随心所欲。
    猜你喜欢
    • 1970-01-01
    • 2022-12-15
    • 2021-12-19
    • 2016-03-21
    • 2021-07-27
    • 2021-12-06
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多