[英]Call App's forceUpdate in a non react component without passing App as property
I have a module which is not a react component (let's call it A) but its variables get displayed by react. 我有一个模块,它不是React组件(我们称它为A),但是它的变量由react显示。 Now A has to call the forceUpdate function of App.js.
现在,A必须调用App.js的forceUpdate函数。 But I don't want to pass always App.js as a property when I create a new object of A.
但是我不想在创建A的新对象时始终将App.js作为属性传递。
I've created following: 我创建了以下内容:
App.js: App.js:
let forceUpdateCaller;
export default class App extends React.Component {
static forceUpdate = () => {
if (forceUpdateCaller) {
forceUpdateCaller();
}
}
forceUpdateCaller = () => {
this.forceUpdate();
}
constructor(props) {
super(props);
forceUpdateCaller = this.forceUpdateCaller;
}
...
}
A: A:
import App from "../App";
export default class A extends ...{
constructor() {
super();
}
updateContent = () => {
...
App.forceUpdate();
}
}
But I'm sure, there's a better, cleaner way. 但我敢肯定,有一种更好,更清洁的方法。 Do you have any ideas?
你有什么想法?
Found the best way: 找到了最好的方法:
export let ref;
class App extend React.Component{
constructor(props){
super(props);
ref = this;
}
}
Now I have full access to the App object when I import {ref}
. 现在,我在导入
{ref}
时可以完全访问App对象。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.