react父子组件相互传值


1、父组件------>子组件
通过父组件设置(state) --------->子组件 (this.props.show)

子组件

 <ModeView modeName="增 加1" contentName={contentName} show={this.state.showSubDlg} modeOff={this.rmvShow}

2、子组件 (someFn)------->父组件 (fn)
通过设置子组件的props ,然后父组件通过props传到fn

  someFn(curRowData) {
    this.props.pfn(curRowData); // 传给父组件了
  }
(<tr key={index} onClick={ () => {
          {/*alert("你好。2017.1.21----" + index );*/}
          //------------------------------获取一行数据---------------------------------
          curRowData = FeildData[index];
          this.someFn(curRowData);
          
          this.setState({
            curRowData:curRowData,
          },
            () =>{
              console.log("-----------------this1111.curRowData-----------------------");
              console.log(this.state.curRowData);
            }
          );
          console.log("-----------------curRowData-----------------------");
          console.log(curRowData);

        }
          
        } style={{ cursor: 'pointer' }}>
          {cells}
        </tr>);

父组件

  fn = (newState) => {
    this.setState(
      {
      someKey: newState },
      () => {
        console.log("---------龙哥-----------");
        console.log(this.state.someKey);
      }
    );
  }
<TableView key="TableViewHeader" pfn={this.fn} />

---------------------------------setState后边可以带一个函数------------------------------

         this.setState({
            curRowData:curRowData,
          },
            () =>{
              console.log("-----------------this1111.curRowData-----------------------");
              console.log(this.state.curRowData);
            }
          );
 //获取当前选中的一行数据
  // getCurRowData = (dataArr,dataCb) => {
  //   this.setState(
  //     {
  //       curRowData: dataArr,
  //     },
  //     dataCb()
  //   )
  // }

总结: 子组件传值给父组件
思想是回调函数:
也就是在父组件中,设置一个函数,这个函数就是操作回调的数据

<TableView key="TableViewHeader" pfn={this.fn} />
  //------------------接收子组件返回的修改页面数据---------------------
  fn = (curRowAllShowData,curRowAllData) => {
    this.setState(
      {
      xiuGaiShowData: curRowAllShowData ,
      xiuGaiRowAllData :curRowAllData ,
      },
    );
  }

子组件

(<tr key={index} onClick={ () => {
        //------------------------------获取一行数据---------------------------------
          curRowAllData = FeildData[index];
          curRowAllShowData = allShowData[index];
          {/*this.someFn(curRowAllShowData,curRowAllData);*/}
          this.props.pfn(curRowAllShowData,curRowAllData);
        }
        } style={{ cursor: 'pointer' }}>
          {cells}
        </tr>);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容