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

How can I store the selected semantic UI dropdown option in state?

我有一个包含 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'
}

我的列表(来自semantic-ui)

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

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

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

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

将其作为道具添加到您的下拉列表中:

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

您可以添加一个 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>
    );
  }
}

使用 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

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

onChange(selectedValue) {

  this.setState({listValue: selectedValue});

}