为什么我不能从ReactJS中的“外部”访问组件方法?为什么不可能,有什么办法可以解决
以代码为例:
var Parent=React.createClass({
render:function(){
var child=<;child/>;;
返回(
<;div>;
{child.someMethod()}//expect“bar”出现“not a function”错误。
<;/div>;
);
}
});
var Child=React.createClass({
render:function(){
返回(
<;div>;
福
<;/div>;
);
},
someMethod:function(){
返回“bar”;
}
});
React.renderComponent(<;Parent/>;,document.body);
React通过ref属性为您尝试执行的操作提供一个接口。为组件分配一个ref,其current属性将是您的自定义组件:
类父类扩展React.class{
建造师(道具){
这个。_child=React.createRef();
}
componentDidMount(){
console.log(this._child.current.someMethod());//打印“bar”
}
render(){
返回(
<;div>;
<;Child ref={this.\u Child}/>;
<;/div>;
);
}
}
注意:根据以下文档,仅当子组件声明为类时,此操作才有效:https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component
更新2019-04-01:更改示例,以使用类和createRef,根据最新的React文档。
更新2016-09-19:将示例更改为根据ref字符串属性文档中的指南使用ref回调。