React.js - 访问组件方法 [英] React.js - access to component methods
问题描述
为什么我不能在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
回调,它将在呈现时通过对组件的引用进行调用:
React provides an interface for what you are trying to do via the ref
attribute. Assign a component a ref
callback, and it will be called with a reference to the component when it is rendered:
var Parent = React.createClass({
componentDidMount: function() {
console.log(this._child.someMethod()); // Prints 'bar'
},
render: function() {
return (
<div>
<Child ref={(child) => { this._child = child; }} />
</div>
);
}
});
更新2016-09-19: 更改示例使用根据的指导,参考回调而非字符串参考参考
字符串属性文档。
注意 :这仅在子组件声明为类时才有效,如下所示: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-到一个组件
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
这篇关于React.js - 访问组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!