【问题标题】:React handling outside clicks to close custom button menu component反应处理外部点击以关闭自定义按钮菜单组件
【发布时间】:2019-06-14 17:30:33
【问题描述】:

我创建了一个按钮菜单组件,它充当简单的“操作”菜单,可在表格中按行使用。我在处理外部点击以在菜单可见时关闭菜单时遇到问题。我目前有一个在单击按钮时附加的侦听器,并且在仅呈现单个按钮菜单组件时它可以正常工作。然而,当我有多个被渲染(比如在一个表中)时,它们都会对相同的事件做出反应 - 即。用户在外面点击,他们都同时打开/关闭。我怎样才能让他们都单独响应?

我在下面的示例代码:

export default class MenuButton extends React.Component {
    constructor(props) {
        super(props);

        this.node = React.createRef();

        this.state = {
            showMenu: false,
        }
    }

    handleOutsideClick = (e) => {
        // Ignore clicks on the component itself
        if (this.node.current.contains(e.target)) {
            return;
        }

        this.handleButtonClick();
    }

    handleButtonClick = () => {
        if (!this.state.show) {
            // Attach/remove event handler depending on state of component
            document.addEventListener('click', this.handleOutsideClick, false);
        } else {
            document.removeEventListener('click', this.handleOutsideClick, false);
        }

        this.setState({
            showMenu: !this.state.showMenu,
        });
    }

    render() {
        return (
            <div>
                <Button
                    text="Actions"
                    onClick={this.handleButtonClick}
                    ref={this.node}
                    menuTrigger
                />
                <Menu anchor={this.node.current} visible={this.state.showMenu}>
                    <Menu.Group title={this.props.groupTitle}>
                        {this.props.children}
                    </Menu.Group>
                </Menu>
            </div>
        )
    }
}

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

    所以我的问题是由于我注意到我的代码中的拼写错误。我有一个showMenu 状态,但在我的handleButtonClick 中,我检查的是this.state.show 而不是this.state.showMenu

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 2021-05-24
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多