[英]how to set value in react-select
react-select中如何通過id設置值 比如我想根據id的值得到select label的值。 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}
/>
);
}
}
在這里你可以看到我的CodeSandbox 。 預先感謝您的幫助和指導
請檢查這個例子:
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"));
在這里你可以看到我的CodeSandbox。
react-select 返回整個 object {id, value, label} onChange。 設置選定的 label 值
handleChange = selectedOption => {
this.setState({ selectedOption: selectedOption.value }); // selected option value
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.