我有在它上面的一个终极版的容器,我想要处理上滚动事件作出反应成分:将事件处理程序添加到纯React组件中?
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
未绑定到什么时候this.props.stepForward()
最后被称为事件的一部分。
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>;
}
}
但据我了解它(告诉我,如果我错了),这不再是一个纯粹的功能组件,和终极版真希望我是用纯组分只要有可能。
是否有一种模式可以将此事件处理程序添加到我的组件,而无需求助于显式构造函数?
从扩展React.Component开始,它就从一开始就是无状态的,它为您提供了生命周期方法。如果你想要一个纯粹的,无状态的组件,它只是const'SomeComponent =(props)=> {props.stuff} )' – lux
我明白了。我误解了[函数组件](https://facebook.github.io/react/tutorial/tutorial.html#functional-components)的格式,谢谢。 –