我有在它上面的一個終極版的容器,我想要處理上滾動事件作出反應成分:將事件處理程序添加到純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)的格式,謝謝。 –