[英]Why i can't access my two container's current target value using react js on making outside click?
使用这个https://codedaily.io/tutorials/Create-a-Dropdown-in-React-that-Closes-When-the-Body-is-Clicked我找到了我的解决方案,让我的下拉菜单在点击时关闭外面的任何地方。
但问题是,我有两个相似的下拉组件来获得这个应用,所以当我应用我的最后一个下拉菜单时,我的最后一个下拉菜单工作正常但不是第一个。我不明白为什么? 谁能帮我解决这个问题。
this.container = React.createRef();
this.state = {
open: false,
};
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
handleClickOutside = (event) => {
if (
this.container.current &&
!this.container.current.contains(event.target)
) {
this.setState({
open: false,
});
}
};
在我的身体 div 处,
<div className="container" ref={this.container}>
{this.state.open && <div>mydropdown1</div>}
</div>
<div className="container" ref={this.container}>
{this.state.open && <div>mydropdown2</div>}
</div>
或者我可以使用 react-foco 吗?
您需要考虑以下几点才能完成工作,
两个下拉容器的两个单独的参考。
维护两个不同的 state 变量
需要在handleClickoutside 和handleButtonClick 方法中分别处理refs 和button click 的情况。 参考下面的代码
container1 = React.createRef(); container2 = React.createRef(); state = { open1: false, open2: false, }; componentDidMount() { document.addEventListener('mousedown', this.handleClickOutside); } componentWillUnmount() { document.removeEventListener('mousedown', this.handleClickOutside); } handleClickOutside = (event) => { if ( this.container1.current &&.this.container1.current.contains(event.target) ) { this:setState({open1; false}). } if ( this.container2.current &&.this.container2.current.contains(event:target) ) { this;setState({open2; false}). } }: } handleButtonClick = (containerNumber) => { this.setState({[containerNumber]; ;this.state[containerNumber]}); }; // your code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.