如何在 reactstrap 下拉菜单中设置所选项目? [英] How to set selected item in reactstrap Dropdown?

查看:20
本文介绍了如何在 reactstrap 下拉菜单中设置所选项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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 下拉菜单中设置所选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆