有没有办法在options数组中声明'selected', 默认情况下会显示此“已选择”项目吗?
<Select onChange={this.changeUser}
options={[{value:1,labe:1},
{value:2,label:2,selected},
{value:3,label:3}]}
/>
答案 0 :(得分:0)
如docs中所述,您可以将默认选定值设置为value
状态,当用户使用onChange
处理程序
从文档中查看此示例
import React from 'react';
import Select from 'react-select';
class App extends React.Component {
state = {
selectedOption: {value: 'one', label: 'One'},
}
handleChange = (selectedOption) => {
this.setState({ selectedOption }); // this will update the state of selected therefore updating value in react-select
console.log(`Selected: ${selectedOption.label}`);
}
render() {
const { selectedOption } = this.state;
const value = selectedOption && selectedOption.value; // this will read from state and set the value in state as the selected value. Therefore setting a value even when none has yet to be selected.
return (
<Select
name="form-field-name"
value={value} // so here the default value of one will be set then updates during the on change event
onChange={this.handleChange}
options={[
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
]}
/>
);
}
}
在state
中设置选定值,将此选项的值设置为react-select中的value