React

2016-03-03 29 views
3

在父級中調用在父級中定義的事件處理函數在我的redux/react應用程序中,我有一個父組件SourceList,其中包含類型爲SourceItem的子項。我決定(並不確定是否對react/redux真的如此)讓子控件不知道點擊處理程序是什麼,並將點擊事件處理程序從父項傳遞給子項。React

我還是很新的終極版/反應和代碼就像下面

componentDidMount() { 
    const { actions } = this.props; 
    if(this.props.side === 'right') { return; } 
    actions.fetchSources(); // this works perfectly 
} 

handleChildClick(source) { 
    const { actions } = this.props; 
    if(this.props.side === 'right') { 
    actions.changeRight(source); 
    return; 
    } 
    actions.changeLeft(source); 
} 

render() { 
    const { actions } = this.props.actions; 
    var that = this; 
    var rightSide = this.props.side === 'right'; 
    var sources = this.props.sources.items.map(function(source) { 
    return <SourceItem 
       key={source.id} 
       onClick={that.handleChildClick.bind(that, source)} 
       source={source}/>; 
    }); 
    return <ul>{sources}</ul> 
} 

actions勢必行動創作者bindActionCreators

和子組件剛剛從props得到的值:

class SourceItem extends React.Component { 
    render() { 
    const { onClick, selected, source } = this.props; 
    return <li onClick={onClick}>{source.name}</li> 
    } 
} 

雖然這個工程,我不想保留對的參考在that中,並調用bind函數,如that.handleChildClick.bind(that, source)是正確的還原/反應方式。

感謝您的幫助!

+0

終極版教程給出了完全一樣的情況的例子 - http://redux.js.org/docs/basics/UsageWithReact.html –

+1

只是想補充一點,你可以爲函數使用ES6語法並執行'handleChildClick =(source)=> {...}'而不是'handleChildClick(source){...}'。有了這個'this'將引用正確的對象,你不需要做'that = this'。只是一個側面說明。 – Chris

+0

@LaFaulx,我知道那個教程,但代碼有不同 - 那裏的類以不同的方式定義,我很困惑:) –

回答

1

一個好方法是在構造函數中定義handleChildClick,這是爲了防止每次通過onClick調用函數時都會重新創建函數。要使用this => that解決問題,請使用箭頭功能。

constructor([props]) { 
    this.handleChildClick = this.handleChildClick.bind(this) 
} 

.... 
render() { 
    const { actions } = this.props.actions; 
    var rightSide = this.props.side === 'right'; 
    var sources = this.props.sources.items.map((source) => { 
    return <SourceItem 
      key={source.id} 
      onClick={this.handleChildClick} 
      source={source}/>; 
    }); 
    return <ul>{sources}</ul> 

}

..... 

class SourceItem extends React.Component { 
    render() { 
    const { onClick, selected, source } = this.props; 
    return <li onClick={onClick(source)}>{source.name}</li> 
    } 
}