REACT-SELECT:有没有办法在选项中声明'selected'?
REACT-SELECT: Is there a way to declare 'selected' in options?
有没有办法在选项数组中声明 'selected',
这个 'selected' 项目会默认显示吗?
<Select onChange={this.changeUser}
options={[{value:1,labe:1},
{value:2,label:2,selected},
{value:3,label:3}]}
/>
如 docs 中所述,您可以将默认 selected 值设置为 value
状态,当用户使用 [= 切换到备用选项时,您可以更新该状态12=] 处理程序
看看文档中的这个例子
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
中设置一个 selected 值,在 react-select
中将此选项的值设置为 value
有没有办法在选项数组中声明 'selected', 这个 'selected' 项目会默认显示吗?
<Select onChange={this.changeUser}
options={[{value:1,labe:1},
{value:2,label:2,selected},
{value:3,label:3}]}
/>
如 docs 中所述,您可以将默认 selected 值设置为 value
状态,当用户使用 [= 切换到备用选项时,您可以更新该状态12=] 处理程序
看看文档中的这个例子
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
中设置一个 selected 值,在 react-select
value