use*_*183 161 javascript dom reactjs
为什么我不能在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);
Run Code Online (Sandbox Code Playgroud)
Ros*_*len 187
React通过ref
属性为您尝试执行的操作提供了一个界面.为组件分配一个ref
回调函数,它将在呈现时通过对组件的引用进行调用:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
更新2016年9月19日: 变更例如使用裁判的回调,而不是字符串裁判每指导意见的current
字符串属性文档.
注意:这仅在子组件声明为类时才有效,如下所示:https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a- REF到一类组分
Sjo*_*erd 39
如果要从外部React调用组件上的函数,可以在renderComponent的返回值上调用它们:
var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();
Run Code Online (Sandbox Code Playgroud)
获取React之外的React Component实例句柄的唯一方法是存储React.renderComponent的返回值.来源.
Pau*_*ssy 37
或者,如果Child上的方法是真正的静态(不是当前props,state的产品),您可以在其上定义它statics
,然后像静态类方法一样访问它.例如:
var Child = React.createClass({
statics: {
someMethod: function() {
return 'bar';
}
},
// ...
});
console.log(Child.someMethod()) // bar
Run Code Online (Sandbox Code Playgroud)
从React 16.3开始 React.createRef
可以使用(用于ref.current
访问)
var ref = React.createRef()
var parent = <div><Child ref={ref} /> <button onClick={e=>console.log(ref.current)}</div>
React.renderComponent(parent, document.body)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
136827 次 |
最近记录: |