[英]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.