如何从ReactJS的“外部”访问组件方法? [英] How to access component methods from “outside” in ReactJS?
问题描述
为什么我不能从ReactJS的外部访问组件方法?为什么不可能,有什么办法解决呢?
Why can’t I access the component methods from "outside" in ReactJS? Why is it not possible and is there any way to solve it?
考虑以下代码:
var Parent = React.createClass({
render: function() {
var child = <Child />;
return (
<div>
{child.someMethod()} // expect "bar", got a "not a function" error.
</div>
);
}
});
var Child = React.createClass({
render: function() {
return (
<div>
foo
</div>
);
},
someMethod: function() {
return 'bar';
}
});
React.renderComponent(<Parent />, document.body);
推荐答案
React提供了您要尝试执行的操作的界面通过 ref
属性。为组件分配一个 ref
,其 current
属性将成为您的自定义组件:
React provides an interface for what you are trying to do via the ref
attribute. Assign a component a ref
, and its current
attribute will be your custom component:
class Parent extends React.Class {
constructor(props) {
this._child = React.createRef();
}
componentDidMount() {
console.log(this._child.current.someMethod()); // Prints 'bar'
}
render() {
return (
<div>
<Child ref={this._child} />
</div>
);
}
}
注意:这将仅在子组件被声明为类的情况下才有效,根据此处的文档: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a -class-component
Note: This will only work if the child component is declared as a class, as per documentation found here: 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
字符串属性文档。
这篇关于如何从ReactJS的“外部”访问组件方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!