折腾:
期间,
想要去实现scroll的addEventListener
然后参考别人代码:
componentDidMount() { const elem = ReactDOM.findDOMNode(this.scrollItem); elem.addEventListener(‘scroll’, this.onListScroll); } |
结果报错:
[eslint] Do not use findDOMNode (react/no-find-dom-node)
[eslint] ‘ReactDOM’ is not defined. (no-undef)
preact [eslint] Do not use findDOMNode (react/no-find-dom-node)
preact ReactDOM.findDOMNode
Rule proposal: warn against using findDOMNode() · Issue #678 · yannickcr/eslint-plugin-react
直接就使用之前refs得到的node即可,无需findDOMNode了?
去改为:
componentDidMount() { // const elem = ReactDOM.findDOMNode(this.scrollItem); // elem.addEventListener(‘scroll’, this.onListScroll); console.log(`componentDidMount`); console.log(this.scrollItem); this.scrollItem.addEventListener(‘scroll’, this.onListScroll); } componentWillUnmount() { console.log(`componentDidMount`); console.log(this.scrollItem); // const elem = ReactDOM.findDOMNode(this.scrollItem); // elem.removeEventListener(‘scroll’, this.onListScroll); this.scrollItem.removeEventListener(‘scroll’, this.onListScroll); } |
看看后面是否生效。
然后是可以得到对应的element的:
且页看到了:
reactjs – What is the different ReactDOM.findDOMNode(this.refs.a) vs this.refs.a? – Stack Overflow
之前的ReactDOM.findDOMNode就是用来获得ref的方式
-》所以现在有了新的更好的refs的写法,就可以不用ReactDOM.findDOMNode了。
【总结】
把此处的:
const elem = ReactDOM.findDOMNode(this.scrollItem); elem.addEventListener(‘scroll’, this.onListScroll); |
改为:
this.scrollItem.addEventListener(‘scroll’, this.onListScroll); |
即可。
其中上面的this.scrollItem,是已经用了改进后的refs:
<ul class={style.nn_a_list} ref={(scrollItem) => {this.scrollItem = scrollItem;}} onScroll={this.onListScroll}> |
转载请注明:在路上 » 【已解决】Preact中如何实现ReactJS中的ReactDOM:[eslint] Do not use findDOMNode (react/no-find-dom-node)