【发布时间】:2020-07-30 12:35:06
【问题描述】:
假设我有三个组件,其中 SubMain2 在 SubMain1 内,而 SubMain1 在 Main 内。如何将道具从 SubMain2 传递到 Main 组件?
问题:TypeError:无法读取未定义的属性“handleSubMain1”
主要
class Main extends Component {
constructor(props) {
super(props);
this.handleSubMain1 = this.handleSubMain1.bind(this);
}
handleSubMain1() {
console.log('received props from SubMain1 which is from SubMain2!');
}
render() {
<SubMain1 handleSubMain1={this.handleSubMain1}/>
}
}
SubMain1
class SubMain1 extends Component {
constructor(props) {
super(props);
this.handleSubMain2 = this.handleSubMain2.bind(this);
}
handleSubMain2() {
console.log('received props from SubMain2!');
}
render() {
<SubMain2 handleSubMain2={this.handleSubMain2}/>
}
}
SubMain2
Component SubMain2 extends Component {
constructor(props) {
super(props);
}
render() {
this.props.handleSubMain2();
}
}
我尝试了这种方法,但是我发现 handleSubMain1 函数未定义。我什至尝试将道具从 SubMain2 直接传递给 Main 组件,但是没有运气。
【问题讨论】:
-
实际上,在所有组件中,SubMain2 中的 JSX 无效。组件中传递的道具不是
this.XX。 SubMain1 没有对handleSubMain1Main 做任何事情,试图通过它。 SubMain2 与从 SubMain1 传递的回调相同。 -
道歉,修复了关于 JSX 的问题。
-
SubMain1 正在从 SubMain2 接收道具,问题是我无法将道具从 SubMain1 传递到 Main。或者有没有办法将道具从 SubMain2 直接传递到 Main?
标签: reactjs react-props react-component