如何在 react-select 中通过 id 设置值

how to set value by id in react-select

我使用 react-select.I 有许多 react-select 改变状态内的值 handleChange.And 最后它们被存储在某个地方(为了简化,我写了一个反应-select)。 目前没问题。

export const regionOptions = [
  { id: "1", value: "region 1", label: "region 1" },
  { id: "2", value: "region 2", label: "region 2" },
  { id: "3", value: "region 3", label: "region 3" },
  { id: "4", value: "region 4", label: "region 4" },
  { id: "5", value: "region 5", label: "region 5" },
  { id: "6", value: "region 6", label: "region 6" },
  { id: "7", value: "region 7", label: "region 7" },
  { id: "8", value: "region 8", label: "region 8" }
];

要编辑表格,我想设置react-select,但是通过ID.for example if State.region = 2 react-select 结果 = region2。 提示:不应更改 handleChange。 在这里你可以看到我的 codeSandbox

我对你的codesandbox中的render函数做了一些修改。 react-select 接受值数组和标签对作为选项,因此您需要将区域选项转换为 react-select 可以正确接受的数据。

const tempOptions = regionOptions.map(option => ({
      value: option.id,
      label: option.label
    }));

这一行添加到渲染函数中。

你可以试试这个例子:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import Select from "react-select";

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedOption: ''
    };
  }

  options = [
    { id: "1", value: "Spring", label: "Spring" },
    { id: "2", value: "Summer", label: "Summer" },
    { id: "3", value: "Autumn", label: "Autumn" },
    { id: "4", value: "Winter", label: "Winter" }
  ];

  handleChange = selectedOption => {
    this.setState({ selectedOption });
  };

  render() {
    return (
      <div>
        <Select
          value={this.state.selectedOption}
          onChange={this.handleChange}
          options={this.options}
        />
        <button
          onClick={() => {
            let summer = this.options.find(o => o.id === "2");
            this.setState({ selectedOption: summer });
          }}
        >
          Set Summer
        </button>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById("app"));