![](/img/trans.png)
[英]how to access DOM element outside the component in JS file in ReactJS
[英]How to access component methods from “outside” in 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);
React 通过ref
属性为您尝试执行的操作提供了一个接口。 为组件分配一个ref
,其current
属性将是您的自定义组件:
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-引用到类组件
2019 年 4 月 1 日更新:更改了示例以根据最新的 React 文档使用类和createRef
。
2016 年 9 月 19 日更新:更改示例以根据ref
String 属性文档中的指导使用 ref 回调。
如果你想从 React 外部调用组件上的函数,你可以在 renderComponent 的返回值上调用它们:
var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();
在 React 之外获取 React Component 实例句柄的唯一方法是存储 React.renderComponent 的返回值。 来源。
或者,如果 Child 上的方法确实是静态的(不是当前道具、状态的产物),您可以在statics
上定义它,然后像访问静态类方法一样访问它。 例如:
var Child = React.createClass({
statics: {
someMethod: function() {
return 'bar';
}
},
// ...
});
console.log(Child.someMethod()) // bar
从 React 16.3 React.createRef
可以使用ref.current
,(使用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)
从 React 0.12 开始,API 略有变化。 初始化 myChild 的有效代码如下:
var Child = React.createClass({…});
var myChild = React.render(React.createElement(Child, {}), mountNode);
myChild.someMethod();
你也可以这样做,不确定这是否是一个好的计划:D
class Parent extends Component {
handleClick() {
if (this._getAlert !== null) {
this._getAlert()
}
}
render() {
return (
<div>
<Child>
{(getAlert, childScope) => (
<span> {!this._getAlert ? this._getAlert = getAlert.bind(childScope) : null}</span>
)}
</Child>
<button onClick={() => this.handleClick()}> Click me</button>
</div>
);
}
}
class Child extends Component {
constructor() {
super();
this.state = { count: 0 }
}
getAlert() {
alert(`Child function called state: ${this.state.count}`);
this.setState({ count: this.state.count + 1 });
}
render() {
return this.props.children(this.getAlert, this)
}
}
正如一些评论中提到的, ReactDOM.render
不再返回组件实例。 您可以在渲染组件的根目录时传入ref
回调以获取实例,如下所示:
// React code (jsx)
function MyWidget(el, refCb) {
ReactDOM.render(<MyComponent ref={refCb} />, el);
}
export default MyWidget;
和:
// 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”?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.