调用 App 的 forceUpdate 在非 react 组件中而不将 App 作为属性传递



我有一个模块,它不是反应组件(我们称之为A(,但它的变量通过反应显示。现在 A 必须调用 App.js 的 forceUpdate 函数。但是当我创建一个 A 的新对象时,我不想总是将 App.js 作为属性传递。

我创建了以下内容:

应用.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;
}
...
}

一个:

import App from "../App";
export default class A extends ...{
constructor() {
super();
}
updateContent = () => {
...
App.forceUpdate();
}
}

但我敢肯定,有一种更好、更清洁的方法。你有什么想法吗?

找到了最好的方法:

export let ref;
class App extend React.Component{
constructor(props){
super(props);
ref = this;
}
}

现在,当我导入 App 对象时,我{ref}. :)

最新更新