gpt4 book ai didi

React js 组件中的 javascript addEventListener 不起作用

转载 作者:行者123 更新时间:2023-12-01 00:18:32 24 4
gpt4 key购买 nike

第一次运行程序工作正常。但点击求和或减号按钮后,该函数将不会运行。

componentDidMount() {

if(CONST.INTRO) {

this.showIntro(); // show popup with next and prev btn

let plus = document.querySelector('.introStep-plus');
let minus = document.querySelector('.introStep-minus');

if (plus || minus) {

plus.addEventListener('click', () => {
let next = document.querySelector(CONST.INTRO[this.state.introStep].element);
if (next) {
next.parentNode.removeChild(next);
}

this.setState({
introStep: this.state.introStep + 1
});

this.showIntro();


});
}
}

最佳答案

如 React 文档中所引用:refs and the dom引用 DOM 元素的正确方法是使用react.creatRef()方法,即使这样,文档也建议不要过度使用它:

Avoid using refs for anything that can be done declaratively.

我建议您在 React 组件渲染方法中管理 .introStep-plusintroStep-minus DOM 元素,使用条件渲染,并保持显示的状态并隐藏 .introStep-plus DOM 元素,而不是在 native javascript addEventListener click

中将其删除

这是建议的修改,它可能无法直接工作,因为您没有提供更多上下文以及如何实现整个组件。

constructor() {
...
this.state = {
...
showNext: 1,
...
}
...

this.handlePlusClick = this.handlePlusClick.bind(this);
}

componentDidMount() {
if(CONST.INTRO) {
this.showIntro(); // show popup with next and prev btn
}
}

handlePlusClick(e) {
this.setState({
introStep: this.state.introStep + 1,
showNext: 0,
});
this.showIntro();
});

render() {
...
<div className="introStep-plus" onClick={this.handlePlusClick}></div>
<div className="introStep-minus"></div>
{(this.stat.showNext) ? (<div> NEXT </div>) : <React.fragment />}
...
}

关于React js 组件中的 javascript addEventListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59597459/

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