问题描述
如何在 reactstrap Dropdown 中设置选中项?
How to set selected item in reactstrap Dropdown?
有下拉示例:https://reactstrap.github.io/components/dropdowns/
当我在下拉列表中选择项目时,它不显示.
When I select item in dropdown, it is not displayed.
************************工作解决方案*****************************
*******************Working solution*****************************
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;
推荐答案
在 DropDownItem(在 div 内?)上添加一个 onclick 以更改您的状态.从您的点击事件中设置一个dropDownValue".在您的 dropDownToggle 中,获取您的 state.dropDownValue.
Add an onclick on your DropDownItem (inside a div ?) to change your state. Set a "dropDownValue" from your click event.In your dropDownToggle, get your 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>
当然,不要忘记初始化它并绑定函数让你的 this 工作.
Of course, don't forget to init it and bind the function for your this to work.
这篇关于如何在 reactstrap 下拉菜单中设置所选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!