我想在我的dropdown
中选择默认选项。当我添加所选选项但不使用默认选定选项渲染时,下面的代码有效:
render() {
return (
<Form onSubmit={this.handleFormSubmit}>
<Form.Dropdown
placeholder="Select Options"
fluid multiple selection
options={this.state.options}
onChange={this.handleMultiChange}
/>
<Button type="submit">Submit</Button>
</Form>
);
}
我尝试添加defaultSelectedLabel={this.state.selected}
。
this.state.selected
是一个选项数组,默认选择的值为true:
render() {
return (
<Form onSubmit={this.handleFormSubmit}>
<Form.Dropdown
placeholder="Select Options"
fluid multiple selection
options={this.state.options}
onChange={this.handleMultiChange}
defaultSelectedLabel={this.state.selected}
/>
<Button type="submit">Submit</Button>
</Form>
);
}
但我得到以下警告:
Warning: Failed prop type: Invalid prop defaultSelectedLabel supplied to Dropdown.
我对defaultValue
道具做了同样的事,但得到了同样的错误
如何在dropdown
中获取默认选择的选项?
你离结果不远了。
你可以在defaultValue
道具中提供一系列值为the docs said。
defaultValue {number | string | arrayOf}初始值或值数组(如果是多个)。
这是一个例子:
class YourComponent extends Component {
componentWillMount() {
this.setState({
options: [
{value:'1', text:'A'},
{value:'2', text:'B'},
{value:'3', text:'C'},
],
selected: ['1', '2'], // <== Here, the values of selected options
});
}
...
render() {
return (
<Form onSubmit={this.handleFormSubmit}>
<Form.Dropdown
placeholder="Select Options"
fluid multiple selection
options={this.state.options}
onChange={this.handleMultiChange}
defaultValue={this.state.selected} // <== here the default values
/>
<Button type="submit">Submit</Button>
</Form>
);
}
}
适用于单一选择:
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Form, Button } from 'semantic-ui-react';
import './style.css';
class App extends Component {
componentWillMount() {
this.setState({
options: [
{value:'1', text:'Lamborghini Aventador 2016'},
{value:'2', text:'VW Beetle 1971'},
{value:'3', text:'Ford Mustang'},
],
selected: '1',
});
}
render() {
return (
<div>
<Form onSubmit={this.handleFormSubmit}>
<Form.Dropdown
placeholder="Select Options"
defaultValue={this.state.selected}
fluid selection
options={this.state.options}
/>
<Button type="submit">Submit</Button>
</Form>
</div>
);
}
}
render(<App />, document.getElementById('root'));