如何将选定的语义UI下拉选项存储在状态中?

时间:2019-04-11 13:29:18

标签: javascript reactjs semantic-ui

我有一个包含5个选项的下拉列表。我需要将所选选项另存为listValue

我的选项和状态列表

const options = [
  { key: 1, text: 'OK', value: 1 },
  { key: 2, text: 'Avvikelse', value: 2 },
  { key: 3, text: 'Ej Relevant', value: 3 },
  { key: 4, text: 'Observation', value: 4 },
  { key: 5, text: 'Saknas', value: 5 },
]
export default class ConfirmationModal extends React.Component {
  state = {
  listValue: 'Status'
}

我的列表(来自语义用户界面)

dropDownList = () => (
  <Dropdown
    placeholder={this.state.listValue}
    clearable
    options={options}
    selection
  />
)

如何在我的状态下存储所选选项?

4 个答案:

答案 0 :(得分:1)

您可以添加一个onChange处理程序,并将赋予处理程序的value置于组件状态。

示例

const options = [
  { key: 1, text: "OK", value: 1 },
  { key: 2, text: "Avvikelse", value: 2 },
  { key: 3, text: "Ej Relevant", value: 3 },
  { key: 4, text: "Observation", value: 4 },
  { key: 5, text: "Saknas", value: 5 }
];

class DropdownExampleControlled extends React.Component {
  state = {
    options,
    value: options[0].value
  };

  handleChange = (_e, { value }) => this.setState({ value });

  render() {
    const { value, options } = this.state;
    const currentOption = options.find(o => o.value === value);

    return (
      <Grid columns={2}>
        <Grid.Column>
          <Dropdown
            onChange={this.handleChange}
            options={options}
            placeholder="Choose an option"
            selection
            value={value}
          />
        </Grid.Column>
        <Grid.Column>
          <Segment secondary>
            <pre>Current value: {currentOption.text}</pre>
          </Segment>
        </Grid.Column>
      </Grid>
    );
  }
}

答案 1 :(得分:1)

据我了解,您需要将值保存在状态中,哪个用户选择了? 如果是,则需要一个事件,例如onChange,这意味着用户从列表中选择了该特定选项。并将其设置为状态

onChange(selectedValue) {

  this.setState({listValue: selectedValue});

}

答案 2 :(得分:0)

将此功能添加到您的组件中

handleChange = (_p, { value }) => {
  this.setState({ listValue: value});
};

将其作为道具添加到您的下拉菜单中:

<Dropdown onChange={this.handleChange} placeholder={this.state.listValue} clearable options={options} selection />

答案 3 :(得分:0)

使用setState处理状态管理。简单示例:

示例 Sandbox

const options = [
      { key: 1, text: 'OK', value: 1 },
      { key: 2, text: 'Avvikelse', value: 2 },
      { key: 3, text: 'Ej Relevant', value: 3 },
      { key: 4, text: 'Observation', value: 4 },
      { key: 5, text: 'Saknas', value: 5 },
    ]

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      listValue: ''
    }
  }

  componentWillMount() //before render
  {
    this.setState({
      listValue: options[1].text  //storing text from second line
    })
  }

  render() {
    return (
      <div>
        {this.state.listValue}
      </div>
      );
    }
  }

显示:Avvikelse