首页 > 解决方案 > React-select onchange 事件多重属性

问题描述

这是我的问题/问题。使用当前版本的#react-select,on-change,事件包含值和标签。但是如何设置它以返回更多道具?例如,我正在选择一个邮政编码,但我希望它返回城市和该城市的呼叫代码。我在#react-select 的选项数组中确实有该信息

谢谢你。

标签: reactjsselectreact-select

解决方案


感谢@steve-cutter-blades 的评论,这是正确的,所以我会更新我的答案:

2019 年 12 月 20 日更新

onChange 函数从您作为道具传递的选项中返回完整的 optionObject。因此将返回每个选项中的所有键:

import React, { Component } from "react";
import ReactDOM from "react-dom";

import Select from "react-select";

class App extends Component {

  onChange = (option) => {
    // option.value     -->  "chocolate"
    // option.label     -->  "Chocolate"
    // option.extraInfo -->  "A"
    return option;
  };

  render() {
    const options = [
      { value: "chocolate", label: "Chocolate", extraInfo: "A" },
      { value: "strawberry", label: "Strawberry", extraInfo: "B" },
      { value: "vanilla", label: "Vanilla", extraInfo: "C" }
    ];
    return (
      <div>
        <Select
          options={options}
          onChange={this.onChange}
          isMulti={false}
          closeMenuOnSelect={true}
        />
      </div>
    );
  }
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我之前的答案有效,但解决方法很糟糕。


推荐阅读