2017-04-24 100 views
1

我有在它上面的一个终极版的容器,我想要处理上滚动事件作出反应成分:将事件处理程序添加到纯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>; 
    } 
} 

但据我了解它(告诉我,如果我错了),这不再是一个纯粹的功能组件,和终极版真希望我是用纯组分只要有可能。

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

+1

从扩展React.Component开始,它就从一开始就是无状态的,它为您提供了生命周期方法。如果你想要一个纯粹的,无状态的组件,它只是const'SomeComponent =(props)=> {props.stuff} )' – lux

+0

我明白了。我误解了[函数组件](https://facebook.github.io/react/tutorial/tutorial.html#functional-components)的格式,谢谢。 –

回答

4

如果您需要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扩展你的班级,而不是React.Component。或者,你可以让你的组件成为一个功能而不是一个类。

相关问题