繁体   English   中英

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

[英]how to set value by id in react-select

我使用 react-select。我有许多 react-select,它们通过 handleChange 更改 state 中的值。最后它们存储在某个地方(为了简化,我写了一个 react-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。例如,如果 State.region = 2 react-select Result = region2。 提示:不应更改 handleChange 在这里你可以看到我的codeSandbox

我在您的代码箱中对渲染 function 进行了一些修改。 react-select 接受值数组和 label 对作为选项,因此您需要将区域选项转换为 react-select 可以正确接受的数据。

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

添加此行以渲染 function。

你可以试试这个例子:

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"));
<Select
   options={regionOptions}
   getOptionValue={({ id }) => id}
 />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM