幻 灭 Blog有朋自远方来,不亦乐乎 ?

父子组件传值(子组件传递父组件)

幻灭·2019-07-20 16:07·1441 次阅读

父子组件传值(子组件传递父组件)

父组件js

 

复制代码
import React, { Component } from 'react';
import Son from './Son'
import './Father.css'

class Father extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sonValue: null
        }
    }
    
    
    render() {

        let {sonValue} = this.state;

        return (
            <div className="father">
                <h1>我是父组件</h1>
                <p>接收到的数据为:{sonValue}</p>

                <Son onSend={this.handleAction}/>

            </div>
        );
    }

    handleAction = (data)=>{
        console.log('handleAction执行了');
        this.setState({sonValue: data});
    }

}

export default Father;
复制代码

 

子组件js

 

复制代码
import React, { Component } from 'react';
import './Son.css'

class Son extends Component {

    constructor(props) {
        super(props);
        this.state = {
            inputVal: ''
        }
    }
    

    render() {

        // console.log(this.props.onSend);
        // this.props.onSend(1,2,3,4);

        let {inputVal} = this.state;

        return (
            <div className="son">
                <h1>我是子组件</h1>

                <input type="text" value={inputVal} onChange={this.changeAction}/>
                <button onClick={()=>{
                    //调用父组件的函数,传入参数,实现子组件向父组件的传值
                    this.props.onSend(inputVal);
                }}>发送</button>

            </div>
        );
    }

    changeAction = (ev)=>{
        this.setState({inputVal: ev.target.value});
    }
}

export default Son;
复制代码

 

父组件css

 

.father{
    padding: 50px;
    background: lemonchiffon;
}

 

子组件css

 

 

.son{
    padding: 30px;
    background: lightblue;
}

 

posted @   前端小菜鸟吖  阅读(1441)  评论(0编辑  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具
· Vue3封装支持Base64导出的电子签名组件
点击右上角即可分享
微信分享提示