REACT-SELECT:有没有办法在选项中声明'选中'?

时间:2018-01-28 09:57:47

标签: reactjs react-select

有没有办法在options数组中声明'selected', 默认情况下会显示此“已选择”项目吗?

<Select onChange={this.changeUser}
 options={[{value:1,labe:1},
           {value:2,label:2,selected},
           {value:3,label:3}]}
/>

1 个答案:

答案 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