【问题标题】:Adding an event handler to a pure React component?向纯 React 组件添加事件处理程序?
【发布时间】: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) =&gt; &lt;span&gt;{props.stuff}&lt;span&gt;)
  • 我明白了。我记错了functional component 的格式,谢谢。

标签: javascript reactjs redux components react-redux


【解决方案1】:

如果您需要 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>;
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2011-03-10
    相关资源
    最近更新 更多