为什么我不能在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);
正如在一些评论中提到的,ReactDOM。渲染不再返回组件实例。你可以在呈现组件的根时传入一个ref回调来获取实例,如下所示:
// React code (jsx)
function MyWidget(el, refCb) {
ReactDOM.render(<MyComponent ref={refCb} />, el);
}
export default MyWidget;
and:
// vanilla javascript code
var global_widget_instance;
MyApp.MyWidget(document.getElementById('my_container'), function(widget) {
global_widget_instance = widget;
});
global_widget_instance.myCoolMethod();
正如在一些评论中提到的,ReactDOM。渲染不再返回组件实例。你可以在呈现组件的根时传入一个ref回调来获取实例,如下所示:
// React code (jsx)
function MyWidget(el, refCb) {
ReactDOM.render(<MyComponent ref={refCb} />, el);
}
export default MyWidget;
and:
// vanilla javascript code
var global_widget_instance;
MyApp.MyWidget(document.getElementById('my_container'), function(widget) {
global_widget_instance = widget;
});
global_widget_instance.myCoolMethod();
另一种方法很简单:
函数外:
function funx(functionEvents, params) {
console.log("events of funx function: ", functionEvents);
console.log("this of component: ", this);
console.log("params: ", params);
thisFunction.persist();
}
绑定:
constructor(props) {
super(props);
this.state = {};
this.funxBinded = funx.bind(this);
}
}
请在这里查看完整的教程:如何从外部使用React组件的“this”?