父子组件传值(子组件传递父组件)
父组件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; }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具
· Vue3封装支持Base64导出的电子签名组件