javascript - ES6 类为自身调用 SetState 函数
问题描述
我正在构建一个 React 应用程序并尝试查看是否可以执行以下操作。有很多嵌套组件,并且正在更新的组件始终是最顶层的父组件。
这个想法是通过 ES6 类原型化的嵌套对象来构建它,如下所示:
class _Board {
constructor(setStateFunction){
this.items = [];
this.setState = setStateFunction;
}
addSwimlane() {
console.log(this);
this.items = [...this.items, new _Swimlane()];
this.setState(this);
}
}
class _Swimlane {
constructor(){
this.id = uuidv4();
this.items = [];
}
addColumn() {
this.items = [...this.items, new _Column(this.id)];
//Can we call the parent function through super to update the render?
}
}
然后我有我的组件,我将在其中调用该函数:
const Main = (props) => {
const [board, setBoard] = useState(new _Board());
useEffect(() => { //Initial Render load setState
setBoard(new _Board(setBoard));
}, []);
return (
<div className="App" >
{JSON.stringify(board)}
<button onClick={() => board.addSwimlane()} >Add Swimlane</button>
</div>
);
};
我有两个问题:
- 你如何在一个类中传递这样的函数?我可以像往常一样通过箭头函数传递它们,但是当作为参数传递时,渲染不会更新。
- 一旦孩子嵌套,你如何调用父类?我应该通过我已经拥有的“addX”函数传递该函数并将其作为参考吗?
解决方案
推荐阅读
- rider - 在 JetBrains Rider 中,有没有办法在不关闭正在运行的项目的情况下运行复合运行/调试配置?
- qt - QML中Window和ApplicationWindow的区别?
- c++ - 带字符串的 C++ 构造函数
- azure - 如何在 ServiceBus ManagementClient CreateSubscriptionAsync 上设置 TTL
- angular - RxJS forkjoin observables 未检索
- python - 对没有双精度的数组求和
- google-apps-script - 无法读取 null 的属性“getEvents”-> 当日历的非所有者尝试删除事件时
- c# - C# 调用 Jupyter Notebook
- sql-server - org.hibernate.exception.SQLGrammarException:将 nvarchar 值“ViewWebApp”转换为数据类型 int 时转换失败
- php - DateTime('now') 在 sleep() 之后未修改