【发布时间】:2021-03-04 07:59:56
【问题描述】:
在两层上调用父母方法时遇到问题。 它要么什么都不做,要么说它不是一个函数。所以这是我的子组件:
class Child extends React.Component {
render() { //return some awesome HTML, that at some point calls doStuff }
doStuff() {
//do some stuff
this.props.parentState.notifyParent();
}
}
我的父组件现在有了一些条件性的东西,所以它看起来像这样:
class Parent extends React.Component {
constructor(props : any) {
super(props);
this.state = {
//setSomeProps
updateParent: this.updateParent
};
}
determineUsedComponent(props: any) {
//some conditions
return <Child parentState={props}/>
}
updateParent() {
console.log("Update parent");
}
render() {
return (<this.determineUsedComponent props={this.state}/>)
}
}
我还尝试将函数作为单个对象提供给孩子。做的东西看起来如下:
doStuff() {
props.notifyParent()
}
而父组件则具有以下签名的确定UsedComponent方法:
determineUsedComponent(props: Any, updateParent: Function) {}
它被调用:
<this.determineUsedComponent props={this.state} updateParent={this.updateParent}/>
如果我尝试在 determineUsedComponent 方法中像属性一样插入它:
return <Child parentUpdate={this.parentUpdate}/>
它再次抛出异常“this.props.notifyParent() not a function”。 相反,如果我这样写:
return <Child parentUpdate={()=>this.parentUpdate}/>
没有错误,只是什么也没发生。 (也没有日志。) 我非常无能,现在尝试了如何编写函数并将其提供给孩子的所有可能选项,但有些人给出了错误(以上两个)并且大多数人根本没有做任何事情。 有任何想法吗? 值得一提的是:子组件是用纯 JS 编写的,而父组件是用 Typescript 编写的。
【问题讨论】:
-
不会撒谎,这是一个扭曲的模式!虽然不知道其中的原因,所以我无法判断,虽然很可能是failing to keep the right context somewhere (the
this). -
原因是我需要条件检查,应该使用哪个组件取决于父组件中的一些referenceStats。希望我也可以在两者之间留下这种方法。这给了我一个想法,降低了可读性,但删除了一层……但是,如果有一些理由让它与两层一起工作,那还是很好的。 :D
标签: javascript reactjs typescript methods callback