向纯 React 组件添加事件处理程序?

Adding an event handler to a pure React component?

我有一个 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 真的希望我尽可能使用纯组件。

是否有一种模式可以将此事件处理程序添加到我的组件中而无需求助于显式构造函数?

如果您需要 DOM 事件的处理程序,您的组件可能太复杂而不能成为一个纯组件。没有组件 必须 是纯组件(对于 React、Redux 或任何相关库),它只是理想的,因为它们往往更简单,并且在未来的 React 版本中将具有性能优势。要修复此组件,请将其更改为:

import React from 'react';

export default class Visualization extends React.Component {
    constructor() {
        super();
        this.handleScroll = this.handleScroll.bind(this);
    }

    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
        }
    }

    render() {   
        return <div onWheel={handleScroll}>"HELLO WORLD"</div>;
    }
}

P.S。如果您希望此组件是纯的,请从 React.PureComponent 扩展您的 class,而不是 React.Component。或者,您可以将组件设为函数而不是 class.