2017-04-24 99 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。或者,你可以讓你的組件成爲一個功能而不是一個類。

相關問題