react父子组件通信

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_45115705/article/details/102622962

在 React 中,数据是自顶而下单向流动的,即从父组件到子组件。
所以就存在父子组件之间的通信的必要性了。

父组件.jsx

import React from 'react';
import Child from './child'

class Father extends React.Component {
    constructor(props){
        super(props);
        this.state={
            msg:'我是父组件的信息',
            name:'父组件',
            age:10000
        }
    }
    callback=(msg,name,age)=>{
        // setState方法,修改msg的值,值是由child里面传过来的
        this.setState({msg,name,age});
    }

  render() {
    return (
      <div className="Father">
        <p> Message: {this.state.msg}</p>
        <Child 
        	// 父组件向子组件通信(传值)
	        callback={this.callback} 
	        age={this.state.age} 
	        name={this.state.name}>
        </Child>
      </div>
    );
  }
}

export default Father;

子组件.jsx

import React from "react";

class Child extends React.Component{
    constructor(props){
        super(props);
        this.state={
            name:'子组件',
            age:8,
            msg:"我是子组件的消息"
        }
    }

    change=()=>{
	// 子组件向父组件通信(传值)      
		this.props.callback(this.state.msg,this.state.name,this.state.age);
    }

    render(){
        return(
            <div>
           		 //在子组件中,通过 this.props.name  this.props.age就能拿到父组件里面的数据
                <div>{this.props.name}</div>
                <div>{this.props.age}</div>
                <button onClick={this.change}>点击</button>
            </div>
        )
    }
}

export default Child;
PS:未来的你,一定会感谢今天拼命努力的自己!

猜你喜欢

转载自blog.csdn.net/weixin_45115705/article/details/102622962