[英]Call App's forceUpdate in a non react component without passing App as property
我有一個模塊,它不是React組件(我們稱它為A),但是它的變量由react顯示。 現在,A必須調用App.js的forceUpdate函數。 但是我不想在創建A的新對象時始終將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:
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;
}
}
現在,我在導入{ref}
時可以完全訪問App對象。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.