我尝试访问子组件的方法。 看起来像这样: 1.通过组件的引用名称和方法
来调用方法Form.js
this.ref.details.getDataFromComponent();
<Details
pointToShow={this.state.point}
ref="details"
/>
Details.js
getDataFromComponent() {
//do my stuff get state and connect to get data for component Details
}
我一直有&#34; Uncaught TypeError:无法读取属性&#39; ref&#39; of null&#34; 反应15.4.2
答案 0 :(得分:1)
要访问组件的参考,您需要使用this.ref
,而不是this
。
但是,这似乎不是问题,因为当您尝试访问时,错误明确表示null
为{{1}}。要确定原因,我们需要查看更多代码。
您还应该考虑使用ref callback attribute而不是您的方式来定义引用,因为不再推荐使用此语法,并且可能会在将来的版本中将其删除。
答案 1 :(得分:0)
正如Timo提到使用refs
访问元素时,你应该写this.refs...
根据错误,您无权访问this
。很可能您在方法内部调用this.ref.details.getDataFromComponent();
而无法访问this
例如你写:
callRef() {
this.ref.details.getDataFromComponent();
....
}
如果是,那么您无法访问this
。您应该使用this
绑定您的函数
您可以使用箭头功能自动绑定this
:
callRef = () => {
this.ref.details.getDataFromComponent();
....
}
注意:要使用箭头功能,您需要在webpack配置中使用babel加载程序。
或者你可以在调用方法时绑定。
例如,您应该在jsx代码中调用callRef()
方法,如下所示:
< ... onClick={this.callRef.bind(this)} />