2017-06-05 91 views
2

如何在reactstrap Dropdown中设置选定的项目?如何在reactstrap Dropdown中设置选定的项目?

有例如下拉的:https://reactstrap.github.io/components/dropdowns/

当我选择下拉列表项,它不显示。

*******************工作液************************* ****

import React from "react"; 
import {ButtonDropdown, DropdownItem, DropdownMenu, DropdownToggle} from "reactstrap"; 
import superagent from "superagent"; 

class BootstrapSelect extends React.Component { 

    constructor(props) { 
     super(props); 

     this.toggle = this.toggle.bind(this); 
     this.changeValue = this.changeValue.bind(this); 
     this.state = { 
      actions: [], 
      dropDownValue: 'Select action', 
      dropdownOpen: false 
     }; 
    } 

    toggle(event) { 

     this.setState({ 
      dropdownOpen: !this.state.dropdownOpen 
     }); 
    } 

    changeValue(e) { 
     this.setState({dropDownValue: e.currentTarget.textContent}); 
     let id = e.currentTarget.getAttribute("id"); 
     console.log(id); 
    } 


    componentDidMount() { 
     superagent 
      .get('/getActions') 
      .type('application/json; charset=utf-8') 
      .end(function (err, res) { 
       console.log(res.body); 
       this.setState({actions: res.body}); 
      }.bind(this)); 

    } 

    render() { 
     return (
      <ButtonDropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}> 
       <DropdownToggle caret> 
        {this.state.dropDownValue} 
       </DropdownToggle> 
       <DropdownMenu> 
        {this.state.actions.map(e => { 
         return <DropdownItem id={e.id} key={e.id} onClick={this.changeValue}>{e.name}</DropdownItem> 
        })} 
       </DropdownMenu> 

      </ButtonDropdown> 
     ); 
    } 

} 

export default BootstrapSelect; 

回答

5

添加一个onclick您DropDownItem(一个div里面?)改变你的状态。从您的点击事件中设置“dropDownValue”。 在你的dropDownToggle中,获取你的state.dropDownValue。

事情是这样的:

changeValue(e) { 
    this.setState({dropDownValue: e.currentTarget.textContent}) 
} 

<DropdownToggle caret> 
    {this.state.dropDownValue} 
</DropdownToggle> 
<DropdownItem> 
    <div onClick={this.changeValue}>Another Action</div> 
</DropdownItem> 

当然,不要忘了初始化,并绑定功能,为你的这个工作。

+0

我添加id来DropdownItem获得选择的菜单项的ID。 – user657009

相关问题