[英]how to set value by id in react-select
I use react-select.I have a number of react-select that change the values inside the state by handleChange.And finally they are stored somewhere(To simplify, I wrote a react-select).我使用 react-select。我有许多 react-select,它们通过 handleChange 更改 state 中的值。最后它们存储在某个地方(为了简化,我写了一个 react-select)。 So far no problem.到目前为止没问题。
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" }
];
To edit the form, I want to set the react-select, but by ID.for example if State.region = 2 react-select Result = region2.要编辑表单,我想设置 react-select,但是通过 ID。例如,如果 State.region = 2 react-select Result = region2。 tip:handleChange should not be changed .提示:不应更改 handleChange 。 Here you can see my codeSandbox在这里你可以看到我的codeSandbox
I did some modification in the render function in your codesandbox.我在您的代码箱中对渲染 function 进行了一些修改。 react-select accepts array of value and label pairs as options so you need to convert the region options to the data that react-select can accept correctly. react-select 接受值数组和 label 对作为选项,因此您需要将区域选项转换为 react-select 可以正确接受的数据。
const tempOptions = regionOptions.map(option => ({
value: option.id,
label: option.label
}));
This line is added to render function.添加此行以渲染 function。
You can try this example:你可以试试这个例子:
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.