React 父子组件之间的通信

584 阅读1分钟

react 单项数据流

react是单项数据绑定 (MVC), 数据流也就是数据传递

父组件可以向子组件传递数据,通过props

父组件 App.js
import React, { Component } from 'react';
import Son from './son';
class App extends Component {
    constructor(props){
        super(props);
        this.state={
            msg:'我是父组件',
            name:'你father',
            age:50
        }
    }

    callback=(msg,name,age)=>{
        // 通过setState方法,修改msg的值,值是由son里面传过来的
        this.setState({msg});
        this.setState({name});
        this.setState({age});
    }

  render() {
    return (
      <div className="App">
        <p>{this.state.msg}</p>
        <Son callback={this.callback} age={this.state.age} name={this.state.name}></Son>
      </div>
    );
  }
}

export default App;
  • 在子组件Son中,如果想拿到父组件里面的属性,就需要通过props传递。
子组件 Son.js
import React from "react";

class Son extends React.Component{
    constructor(props){
        super(props);
        this.state={
            name:'我是孩子组件',
            age:18,
            msg:"给我零花钱"
        }
    }

    change=()=>{
    //在子组件中,通过 {this.props.name}{this.props.age}就能拿到父组件里面的数据。
        this.props.callback(this.state.msg,this.state.name,this.state.age);
    }

    render(){
        return(
            <div>
                <div>{this.props.name}</div>
                <div>{this.props.age}</div>
                <button onClick={this.change}>点击</button>
            </div>
        )
    }
}

export default Son;

子组件向父组件通信

在子组件Son中绑定了onClick事件。 调用this.change方法。
    - 为了保存this指向,可以用箭头函数  thischange=()=>{}
    - 或者在构造器初始化时候通过bind来改变
    - this.change=this.change.bind(this)
    - 或者在onClick方法中绑定this,
    - onClick={this.change=this.change.bind(this)}
    
在change方法中,通过props发送出去一个方法,比如说叫callback方法,父组件中去接收这个方法,callback={this.callback},然后在自身的callback函数中进行一些列操作。