![](/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.