如何以编程方式设置React Dropdown的值

我有这个代码

<Dropdown
    id="city"
    placeholder="Select a city"
    options={this.state.cities}
    onChange={this.onChangeHandler}
    />;

这将显示一个下拉列表,显示占位符“选择一个城市”。

我想要做的是,如果this.state.cities只有一个元素,将其设置为预选。否则,请继续显示占位符文本和下面的所有选项。

我使用的库是https://www.npmjs.com/package/react-dropdown

谢谢


慕桂英3389331
浏览 845回答 2
2回答

翻过高山走不出你

根据文档,该Dropdown组件采用value道具。import Dropdown from 'react-dropdown'import 'react-dropdown/style.css'class App extends React.Component {&nbsp; &nbsp;constructor() {&nbsp; &nbsp; &nbsp;super();&nbsp; &nbsp; &nbsp; this.state={&nbsp; &nbsp; &nbsp; &nbsp; cities: ["New York", "San Francisco", "Seattle", "Washington DC"],&nbsp; &nbsp; &nbsp; &nbsp; selectedCity: ""&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;handleSelectCity = (option)=> {&nbsp; &nbsp; &nbsp; const selectedCity = option.value&nbsp; &nbsp; &nbsp; this.setState({selectedCity});&nbsp; &nbsp;}&nbsp; &nbsp;render() {&nbsp; &nbsp; &nbsp; const {selectedCity, cities} = this.state;&nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Dropdown&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; options={cities}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={this.handleSelectCity}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={selectedCity}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder="Select an option"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp;}}export default App;

慕的地10843

在Dropdown组件中,您可以执行以下操作{(this.props.options.length&nbsp;>&nbsp;1)&nbsp;?&nbsp;<option>{this.props.placeholder}</option>:&nbsp;null}浏览器将自动选择列表中的第一个选项。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript