首页 > 解决方案 > ReactJS:通过 3 个组件传递数据

问题描述

我正在尝试通过层次结构中的 3 个组件(Parent-Child-Child2)传递数据:

父级:

 class Parent extends React.Component {
    constructor(props) {
        super(props);
       this.handleOperation = this.handleOperation.bind(this);
   }

   handleOperation = (value) => {
      // some actions
   };

render() {
       return (
           <div className={styles}>
               <Child valueChild={this.handleOperation()}/>
           </div>
             );
        }
 }

孩子1:

class Child extends React.Component {
constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
}

handleChange =(value) => {
    this.props.valueChild(value);
};

render() {
    return (
          <div>
              <Child2 childValue2 = {this.handleChange} />
          </div>
        );
    }
}

孩子2:

 class Child2 extends React.Component {
constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
}

handleChange =(event) => {
    this.props.childValue2(event.target.value);
};

 render() {
      return (
                <div>
                   <input type="button" onClick={this.handleChange} value="defaultValue" />
               </div>
              );
         }
  }

代码编译成功,但是当我单击输入字段(将值传递给父级)时,我收到以下错误:

错误

标签: reactjscomponents

解决方案


推荐阅读