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

问题描述 投票:1回答:4

我有一个包含5个选项的下拉列表。我需要将选定的选项保存到我的州listValue

My list of options and the state

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'
}

My list (from semantic-ui)

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

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

javascript reactjs semantic-ui
4个回答
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
投票

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

onChange(selectedValue) {

  this.setState({listValue: selectedValue});

}

0
投票

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

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

将其添加为您的Dropdown中的prop:

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

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>
      );
    }
  }

这显示:偏差

© www.soinside.com 2019 - 2024. All rights reserved.