react-select - 如何仅使用 react-select onChange 事件和 value Prop 中的值?

标签 react-select

我尝试在我的 reactjs 应用程序中使用 react-select,但是 onChange 事件有问题。 onChange 应该发送两个参数。第一个应该是选定值,但不是选定值,而是整个选项项作为选定值传递。

例如

  • 我有一系列选项,例如 options=[{ id: '1', name: 'A'},{ id: '2', name:'B'}]
  • 我设置了getOptionValue = (i) => i.id;getOptionLabel = (i)=>i.name;
  • When select the second item onChange(value)作为 value 传递第二个选项参数 ( {id:'2',name:'B'} ) 而不是第二个选项的值 ( '2' )。

  • 这种行为与大多数输入组件不一致。我希望 onChange传递项目的值(value),对于项目本身,我期待另一个事件,如 onItemSelected或类似的东西。

    另外,当我设置 value={'2'} (受控组件),该组件不显示所选项目。

    我必须说我将 AsyncSelect 与 loadOptions 一起使用。

    我怎样才能让它只使用简单的值,而不是选项对象?

    如果这不能发生,我必须放弃另一个类似组件的 react-select。

    最佳答案

    AFAIK 目前没有办法让 React-Select 仅使用值在内部工作。我在我的应用程序中所做的是实现一个层来检索下降的对象,并提取上升的值。像这样的东西(这是简化的,您可能需要更多的验证或处理,具体取决于您的应用程序):

    const Select extends Component {
      handleChange(newSelected) {
        // this.props.handleChange is your own function that handle changes
        // in the upper scope and receives only the value prop of the object
        // (to store in state, call a service, etc)
        this.props.handleChange(newSelected.value);
      }
    
      render() {
        // Assuming you get the simple value as a prop from your store/upper 
        // scope, so we need to retrieve the option object. You can do this in 
        // getDerivedStateFromProps or wherever it suits you best
        const { options, value } = this.props;
        const selectedOption = options.find(option => option.value === value)
    
        <ReactSelect
          options={options}
          value={selectedOption}
          onChange={this.handleChange}
          {...props}
        />
    }
    

    关于react-select - 如何仅使用 react-select onChange 事件和 value Prop 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938331/

    相关文章:

    javascript - react-select 中的 valueComponent 和 valueRenderer 有什么区别?

    reactjs - 在react-select v2 中使用 Font Awesome 图标?

    reactjs - 立即更新 useState

    react-select - 如何关闭菜单 onNewOptionClick?

    reactjs - 在material-ui中使用react选择如何通过仅按一次tab键将焦点移动到下一个控件?

    javascript - 下拉标签输入

    reactjs - react 选择菜单打开/关闭的动画

    javascript - 在弹性容器中进行 react 选择

    ReactJS:在导航栏中使用 Select inside Link 组件时如何避免重定向?