为什么我不能从ReactJS的“外部”访问组件方法?为什么不可能,有什么办法解决呢?
考虑以下代码:
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);
另一种简单的方法:
外部功能:
绑定它:
Please see complete tutorial here: How to use "this" of a React Component from outside?