gpt4 book ai didi

javascript - React 组件 onClick 处理程序不起作用

转载 作者:行者123 更新时间:2023-11-28 07:37:20 24 4
gpt4 key购买 nike

我有一个基本的弹出窗口(图像),当您单击按钮时会出现。当您单击该弹出窗口外部时,它应该关闭,但是当您单击它内部时,它应该保持打开状态并调用测试函数。其初始状态 isPopupVisible 设置为 false。当您单击按钮时,我将状态设置为 true,以呈现弹出窗口。

问题是当您单击图像时,测试函数没有被调用。我认为这是因为状态设置为 false 并且带有 onClick 函数的图像元素最初并未渲染。有谁知道如何解决这个问题吗?

(用 ecmascript 6 编写)

getInitialState () {
return {isPopupVisible: false}
},
onClick () {
if(!this.state.isPopupVisible){
this.setState({isPopupVisible: true});
document.body.addEventListener('click', this.onClickBody)
}
},
onClickBody () {
this.setState({isPopupVisible: false});
document.body.removeEventListener('click', this.onClickBody)
},
test () {
console.log('the onClick from the image works!');
},
showPopup () {
if(this.state.isPopupVisible){
return <div>
<img src='img.png' onClick={this.test} />
</div>
}else{
return null;
}
},
render () {
return (
<span>
<button onClick={this.onClick}>
See Popup
</button>
{this.showPopup()}
</span>
);
}

最佳答案

这有点黑客行为,但是......

onClickBody () {
setTimeout(function(){
if (!this.clickedInBounds && this.isMounted()) {
this.setState({isPopupVisible: false});
document.body.removeEventListener('click', this.onClickBody)
}
this.clickedInBounds = false;
}.bind(this), 0);
},
test () {
console.log('the onClick from the image works!');
this.clickedInBounds = true;
},

setTimeout 只是让它在 test 有机会运行后运行该代码。 isMounted 只是为了在点击 body 和 setTimeout 之间组件被卸载的小可能性。

jsbin

关于javascript - React 组件 onClick 处理程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28448641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com