2017-02-13 77 views
1

在回調中,我希望將道具傳遞給組件,但無法通過this.props,因爲this未定義。ReactJS在回調中訪問「this」

下面是一個簡單的例子:

var MyComponent = React.createClass({ 
    options:{ 
    componentFunction: function(c) { 
     console.log(this.props.myProp); //this references to the options here, not the component itself 
    } 
    }, 
    render: function() { 
    return (
     <OtherComponent options={ this.options } /> 
    ); 
    } 
}); 

而且我通過道具是這樣的:

<MyComponent myProp={"x"}; 

希望得到任何幫助, 感謝。

+0

我強烈建議遷移到ES6語法。使用箭頭函數,這將是沒有問題的。 –

+0

感謝您的建議,將爲我的下一個項目做! – Surreal

回答

2

問題是componentFunction有它自己的範圍。您需要通過添加下面的方法來約束它,你可以做MyComponent

componentWillMount: function() { 
    this.options.componentFunction = this.options.componentFunction.bind(this); 
} 

但是,它可能是更好的使用箭頭功能代替,即沒有限定自己的範圍,因此將繼承this從父範圍。

options:{ 
    componentFunction:() => console.log(this.props.myProp) 
} 
+0

Many謝謝@詹姆斯,這解決了我的問題。更新小提琴:https://jsfiddle.net/gdc2bpw7/ – Surreal

2

使用this.options.bind(this)而不是this.options來訪問this裏面的函數。

或者使用ES6語法 - options =() = {...}

+0

感謝您的快速回復。這是有道理的,但當我嘗試添加此代碼時,我收到以下錯誤消息:** this.options.bind不是函數**。我很快地爲此創建了一個小提琴:https://jsfiddle.net/ayp52sck/ – Surreal

+0

是的,對不起 - 看看@James Brierley的回答 - 您需要使用綁定accordinaly而不是對象, –