2017-02-13 78 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而不是对象, –