react子传父

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

因此要从父组件传递一个方法给子组件,this

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

父组件才能获取到子数据code

例子:blog

子组件 Child.jsget

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.jsclass

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;
相关文章
相关标签/搜索