17

我想在我的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.

我对defaultValueprop 做了同样的事情,但得到了同样的错误

如何在我的dropdown?

4

2 回答 2

27

你离结果不远了。

如文档所述defaultValue,您可以在道具中提供一组值。

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

编辑这是一个活生生的例子

于 2017-08-08T20:30:41.890 回答
2

也适用于单选:

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'));
于 2019-04-23T11:46:32.717 回答