反应处理外部单击以关闭自定义按钮菜单组件

时间:2019-06-14 17:30:33

标签: javascript reactjs react-redux

我有一个创建的按钮菜单组件,它充当一个简单的“动作”菜单,可以在表中按行使用。我在处理可见的外部点击时关闭菜单时遇到问题。我目前有一个单击该按钮时会附加的侦听器,当仅呈现一个按钮菜单组件时,它可以正常工作。但是,当我有多个渲染对象时(例如在表中),它们都对相同事件做出反应-即。用户单击外部,他们都同时打开/关闭。我该如何做,以便他们都能各自做出回应?

下面提供的示例代码:

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>
        )
    }
}

1 个答案:

答案 0 :(得分:-1)

所以我的问题是由于我注意到代码中的错字。我处于showMenu状态,但是在我的handleButtonClick中,我正在检查this.state.show而不是this.state.showMenu

相关问题