假设我有三个组件,其中SubMain2在SubMain1内部,而SubMain1在Main内部。如何将道具从SubMain2传递到Main组件?
问题:TypeError:无法读取未定义的属性'handleSubMain1'
Main
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组件,但是没有运气。
class Main extends Component {
handleSubMain1(arg) {
console.log('received props from SubMain1 which is from SubMain2!');
console.log(arg);
}
render() {
return <SubMain1 handleSubMain1={this.handleSubMain1}/>
}
}
class SubMain1 extends Component {
render() {
return <SubMain2 handleSubMain2={this.props.handleSubMain1}/>
}
}
class SubMain2 extends Component {
handleClick(){
this.props.handleSubMain2('any thing I pass as an argument I can access it in main');
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>
Click me to send data to Main
</button>
)
}
}
down给孩子。行中的每个子组件都需要调用传递给它的回调。
class Main extends Component {
mainCallback = val => console.log("mainCallback", val);
render() {
return <SubMain1 handleSubMain1={this.mainCallback} />;
}
}
class SubMain1 extends Component {
subMain1Callback = val => {
console.log("subMain1Callback");
this.props.handleSubMain1(val);
};
render() {
return <SubMain2 handleSubMain2={this.subMain1Callback} />;
}
}
class SubMain2 extends Component {
subMain2Callback = val => {
console.log("subMain2Callback");
this.props.handleSubMain2(val);
};
render() {
return (
<button onClick={() => this.subMain2Callback(42)}>
SubMain2 - click me?
</button>
);
}
}
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() {
return <SubMain1 handleSubMain1={this.handleSubMain1}/> <-- 2 Change here
}
}
SubMain1:
class SubMain1 extends Component {
constructor(props) {
super(props);
this.handleSubMain2 = this.handleSubMain2.bind(this);
}
handleSubMain2() {
console.log('received props from SubMain2!');
}
render() {
return <SubMain2 handleSubMain2={this.handleSubMain2}/> <-- 2 Change here
}
}
SubMain2:
Component SubMain2 extends Component {
constructor(props) {
super(props);
}
render() {
return this.props.handleSubMain2(); // this function should return jsx
}
}