首页 > 其他 > 详细

react子传父

时间:2019-06-23 18:49:22      阅读:83      评论:0      收藏:0      [点我收藏+]

react里子组件不能直接操作父组件的数据。

所以要从父组件传递一个方法给子组件,

子组件获取到该方法后,把子数据传入该方法,

父组件才能获取到子数据

例子:

子组件 Child.js

import React, { Component } from ‘react‘
class Child extends Component{
    constructor(props){
        super(props)
        this.state = {
            cdata:"子组件数据"
        }
    }
    render(){
        return(
            <div>
                <button onClick={this.trans.bind(this,this.state.cdata)}>确定</button>
            </div>
        )
    }

    //点击子组件时,定义一个方法,调用父组件传过来的方法,把子组件数据传入到这个方法里
    trans(data){
        this.props.content(data)
    }
}
export default Child;

 

父组件App.js

import React, { Component } from ‘react‘;
import Child from ‘./Child‘
class App extends Component{
  constructor(props){
    super(props)
    this.state = {
      pdata:"父组件数据"
    }
  }
  render(){
    return(
      <div>
        {/* 传递一个方法给子组件 */}
        <Child content={this.getValue.bind(this)}></Child>
        {this.state.pdata}
      </div>
    )
  }

  //在方法里传入一个参数,val就是子组件传过来的数据
  getValue(val){
    this.setState({
      pdata:val
    })
  }
}
export default App;

 

react子传父

原文:https://www.cnblogs.com/luguankun/p/11073688.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!