【发布时间】: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