第一次运行时,程序运行正常。但是单击加减按钮后,该功能将无法运行。
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()方法,即使如此,该文档也建议不要过度使用它:
避免将引用用于任何可以声明的方式。
我建议您在条件组件渲染方法中使用条件渲染来管理.introStep-plus
和introStep-minus
DOM元素,并保持状态以显示和隐藏.introStep-plus
DOM元素,而不是在本机javascript addEventListener
中将其删除]点击
这里是建议的修改,由于您没有提供更多的上下文以及如何实现整个组件,因此它可能无法直接使用。
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 />}
...
}