[英]how to set value in react-select
how to set value by id in react-select For example, I want to select the label value according to the value of the ID. react-select中如何通过id设置值 比如我想根据id的值得到select label的值。 id = "2" result = "Summer"
id = "2" 结果 = "夏天"
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 (
<Select
value={this.state.selectedOption}
onChange={this.handleChange}
options={this.options}
/>
);
}
}
Here you can see my CodeSandbox .在这里你可以看到我的CodeSandbox 。 Thank you in advance for your help and guidance
预先感谢您的帮助和指导
Please check 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"));
Here you can see my CodeSandbox.在这里你可以看到我的CodeSandbox。
react-select returns entire object {id, value, label} onChange. react-select 返回整个 object {id, value, label} onChange。 To set selected label value
设置选定的 label 值
handleChange = selectedOption => {
this.setState({ selectedOption: selectedOption.value }); // selected option value
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.