React父子通信

components---》child.js

import React from "react";
class Child extends React.Component{
    state ={
        childname:'子组件名字:qq',
        childage:'子组件年纪:20',
        childmsg:"这是来自子类的消息"
    }
    change = () => {
        this.props.callback(this.state.childmsg,this.state.childname,this.state.childage);
    }
    render(){
        return(
            <div id='a'>
                <div> {this.props.childname}</div>
                <div>{this.props.childage}</div>
                <button onClick={this.change}>点击</button>
            </div>
        )
    }
}
export  default  Child;

parent.js

import React from "react";
import Child from './child'
class Parent extends React.Component{
    constructor(props) {
        super(props);
        this.state={
            msg:'这是父组件的消息',
            name:'父组件名字:蔡蔡',
            age:'父组件年龄:25'

        }
    }
    callbackAAA =(childmsg,childname,childage) => {
        this.setState({
            msg:childmsg,
            name:childname,
            age:childage
        });
    }
    render(){
        return(
            <div id='xxx'>
                <p> Message: {this.state.msg}</p>
                <Child callback={this.callbackAAA} childage={this.state.age} childname={this.state.name} ></Child>
            </div>
        );
    }
}
export default Parent;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Parent from './components/parents';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Parent/>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值