当前位置: 首页 > news >正文

React 组件通信

在这里插入图片描述

父传子

函数式组件

function Footer(props){const [count,setCount] = useState(0)const {name,age} = propsconst onClick = ()=>{setCount(count+1)}return (<div><button onClick={()=>{onClick()}}>点此+1</button><div>{count}</div><div>name是:{name}年龄是:{age}</div></div>)
}

类组件

class Header extends React.Component{constructor(props){super()this.props = props}render(){const {name,age} = this.propsreturn (<div><div>name是:{name}年龄是:{age}</div> </div>)}
}

也可以直接在constructor中super(props)

constructor(props){super(props)}

通信时的属性验证

进行一个typescript的使用

父传子 通过回调函数

类组件中

class CounterButton extends React.Component{constructor(props){super(props)}render(){const {handlecallback} = this.propsreturn (<button onClick={handlecallback}>接口anniu组件</button>)}
}

如图,通过props中父组件传递过来的increase函数实现增加

父组件传值

<CounterButton handlecallback={this.increase}/>

函数式组件中

function DeButton(props){const {handlecallback} = propsreturn (<button onClick={handlecallback}>函数式子减小button</button>)
}

父组件传值

 <DeButton handlecallback={this.decrease}></DeButton>

父传更远的子代的传递 Context

在这里插入图片描述
在这里插入图片描述

相关文章:

  • 解锁K-近邻算法:数据挖掘的秘密武器
  • 使用Trae编辑器与MCP协议构建高德地图定制化服务
  • vscode内嵌浏览器实时预览vue项目
  • Pytorch3D 中涉及的知识点汇总
  • Stable Diffusion 项目实战落地:绘制真人卡通IP形象(一)甄嬛旗装格格:从“真人”到“卡通”化,神奇的转变之旅!
  • 领域驱动设计(DDD)【0】之DDD理论概念认识
  • wordpress外贸独立站常用留言表单插件 contact form 7
  • Linux TCP/IP协议栈中的TCP输入处理:net/ipv4/tcp_input.c解析
  • 人工智能的未来:从“提示即程序”到“部分自治”
  • Kubernetes 节点故障自愈方案:结合 Node Problem Detector 与自动化脚本
  • SQL关键字三分钟入门:INSERT INTO —— 插入数据详解
  • 剑指offer37_数组中出现次数超过一半的数字
  • Rust调用 DeepSeek API
  • Sublime text启用vim
  • Maven-添加子模块
  • Python从入门到实战学习笔记(二)
  • IEC61850 通信协议测试验证方法详解
  • YAML 数据格式详解
  • Python爬虫实战:研究Splinter相关技术
  • 决策树:化繁为简的智能决策利器
  • 上海地产网站建设/郑州网站排名优化外包
  • 网站前缀带wap的怎么做/游戏推广是什么工作
  • 建立网站培训讲义/百度seo排名优化
  • 汽车之家官网首页/用广州seo推广获精准访问量
  • 建设工程监理考试网站/百度数据查询
  • 精美网站建设/百度seo优化怎么做