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

Ale*_*gur 2 javascript components reactjs redux react-redux

我有一个 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>;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,此代码将引发错误,因为this当this.props.stepForward()最终作为事件的一部分被调用。

React 教程通过添加构造函数并在其中调用来处理这种情况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>;
    }
}
Run Code Online (Sandbox Code Playgroud)

但据我所知(如果我错了请告诉我),这不再是一个纯粹的功能组件,而且 Redux 真的希望我尽可能使用纯组件。

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

tay*_*c93 5

如果您需要 DOM 事件的处理程序,您的组件可能太复杂而不能成为纯组件。号成分有是一个纯粹的组件(反应,终极版,或任何相关的库),这只是理想的,因为他们往往是简单的,将有性能优势,在未来的版本中作出反应。要修复此组件,请将其更改为:

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>;
    }
}
Run Code Online (Sandbox Code Playgroud)

PS 如果您希望这个组件是纯的,请从 扩展您的类React.PureComponent,而不是React.Component. 或者,您可以使您的组件成为一个函数而不是一个类。