2017-08-08 144 views
0

我想在我的dropdown中選擇默認選項。下面的代碼的工作,當我添加選定的選項,但不使用默認選擇的選項渲染:語義ui在下拉列表中選擇默認選項

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道具,但得到相同的錯誤

如何在我的中獲得默認選擇的選項?

回答

5

你離結果不遠了。

您可以在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> 
    ); 
    } 
} 

編輯Here is a live example

+0

@ user2456977它爲我工作。我更新了我的答案,提供了一個可以看到我的結果的實例。你可以複製你的選項數據的樣本嗎?我認爲你的'value'鍵有問題 –

+0

最後解決了它 - 我設置了所有這些數據---選項,並在componentWillReceiveProps中選擇了---而不是構造函數或componentWillMount。非常感謝 – user2456977

+0

@ user2456977很高興聽到:)爲了更好地理解你的問題,你可以看看[這裏](https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops):在安裝過程中,React不會使用初始道具調用componentWillReceiveProps –

相關問題