react子传父

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;

使用箭头函数的写法

子组件:

import React, { Component } from 'react';
class Child extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            cdata:"子数据"
         }
    }
    render() { 
        return ( 
            <div>
                子组件
                <button onClick={()=>this.transValue(this.state.cdata)}>传递数据</button>
            </div>
         );
    }
    transValue(val){
        console.log(val);
        
        this.props.content(val)
    }
}
 
export default Child;

父组件

import React, { Component } from 'react';
import Child from './Child'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
        pdata:"父数据"
      }
  }
  render() { 
    return ( 
      <div>
        {this.state.pdata}
        {/* 这个方法要传入参数 */}
        <Child content={(val)=>this.giveMeth(val)}></Child>
      </div>
     );
  }
  giveMeth(val){
    console.log(val);
    
  }
}
 
export default App;
原文地址:https://www.cnblogs.com/luguankun/p/11073688.html