【发布时间】:2017-09-21 11:17:20
【问题描述】:
我有一个 React 组件,上面有一个 Redux 容器,我想在其上处理滚动事件:
import React from 'react';
export default class Visualization extends React.Component {
render() {
function handleScroll(e) {
if (e.deltaY > 0) {
console.log("YO");
this.props.stepForward(); // stepForward inherited from above
} else {
console.log("DAWG");
this.props.stepBack(); // stepBack inherited from above
}
}
return <div onWheel={handleScroll}>"HELLO WORLD"</div>;
}
}
但是,此代码会引发错误,因为当 this.props.stepForward() 最终作为事件的一部分被调用时,this 未绑定到任何东西。
React 教程 handles this case 添加一个构造函数并在其中调用 this.handleClick = this.handleClick.bind(this);。或者,等效地:
import React from 'react';
export default class Visualization extends React.Component {
constructor() {
super();
this.handleScroll = this.handleScroll.bind(this);
}
render() {
function handleScroll(e) {
if (e.deltaY > 0) {
console.log("YO");
this.props.stepForward(); // stepForward inherited from above
} else {
console.log("DAWG");
this.props.stepBack(); // stepBack inherited from above
}
}
return <div onWheel={handleScroll}>"HELLO WORLD"</div>;
}
}
但据我了解(如果我错了请告诉我),这不再是一个纯粹的功能组件,Redux 真的希望我尽可能使用纯组件。
有没有一种模式可以将此事件处理程序添加到我的组件中而无需求助于显式构造函数?
【问题讨论】:
-
它从一开始就不是无状态的,因为你扩展了 React.Component,它为你提供了生命周期方法。如果你想要一个纯粹的、无状态的组件,那就是 const
SomeComponent = (props) => <span>{props.stuff}<span>) -
我明白了。我记错了functional component 的格式,谢谢。
标签: javascript reactjs redux components react-redux