2016-06-10 47 views
0

我想通過內置反應函數通過道具和試圖設置狀態,但我得到this未定義!反應嵌套組件傳遞內置函數(沒有通量)

我這樣試過的東西:

index.js

let somefun = function(){ 
    this.setState({myvar:1}); 
} 

ReactDom.render(<someComponent body={<someOtherComponent1 componentWillUpdate={somefun}/>} />, document.getElementById('someValidID')); 

someOtherComponent1.js

React.createElement(someOtherComponent1, { "className": "someclass"}) 

我的問題是,每當我通過一個內置函數,即,反應原型this中存在的函數總是未定義的。

如何通過道具發送內置函數?

回答

1

熟悉this並傳遞函數很常見的問題。

TL;博士爲了調用setStatethisthis需要其狀態需要更新的組件內部調用。你在組件外面調用它。

someFun是一個新的函數,它在裏面調用了一個函數this。問題是在這種情況下,this是對someFun的引用,而不是您的組件實例。繼續,並把console.log(this)在那裏看到。

我認爲在你的場景中onComponentWillUpdate應該是你的組件內部的一個函數,而不是在它之外聲明的。

render: function() { 
    return (
    <someOtherComponent1 onComponentWillUpdate={function(nextProps, nextState) { 
     // do something here 
     }} 
    /> 
) 

但是,不要忘記你必須在你的子組件中實際調用該函數。

// in someOtherComponent1 
componentWillUpdate: function(nextProps, nextState) { 
    // do something 
    this.props.onComponentWillUpdate(nextProps, nextState) 
} 
+0

感謝您的答案......但我想在這裏工作了一些抽象的。我不想設定sumeFunc內組件...原因是,這個組件是一個可重用的組件,對這個組件唯一動態的是'componentWillUpdate' func,所以我一直在尋找一種方法來從組件外部指定它(將它從父母組件或類似的東西)哈布你有什麼想法如何做到這一點? –

+0

它會這樣工作。只要你的組件總是調用傳遞下來的函數(你甚至可以將它命名爲ComponentWillMount以使其更容易理解),它就可以工作。你想要的是舊的React的mixin方法,但是這些方法已經被支持了。請記住,您可以即時定義onComponentWillMount。查看更新後的答案。 –

0
ReactDom.render(<someComponent body={<someOtherComponent1 yourFn={somefun}/>} />, document.getElementById('someValidID')); 

和內部組件

this.props.yourFn() 
+0

這是行不通的,因爲問題是'someFun'沒有指向'this'的正確指針,所以在子組件中重命名並調用它會做同樣的事情。它需要在組件的實例中定義,以便'this'指向組件。現在,它正在組件外宣佈。 –