React 组件间的通信

React

父传子

实现:

javascript 复制代码
function Son(props){
  return <div>{ props.name }</div>
}
​
​
function App(){
  const name = 'this is app name'
  return (
    <div>
       <Son name={name}/>
    </div>
  )
}

注意:这里可以传递任何类型,包括函数,span盒子等等

特殊:当我们将内容嵌套在子盒子内部时,在子组件里面可以通过props.childern既可以调用数据

如使用时:

javascript 复制代码
<Son name={name}>
    <span>hdfus</span>
</Son>

子传父

子组件调用父组件里面的函数

javascript 复制代码
function Son({ onGetMsg }){
  const sonMsg = 'this is son msg'
  return (
    <div>
      {/* 在子组件中执行父组件传递过来的函数 */}
      <button onClick={()=>onGetMsg(sonMsg)}>send</button>
    </div>
  )
}
或者:
const Son=({ onGetMsg })=>{
      const sonMsg = 'this is son msg'
  return (
    <div>
      {/* 在子组件中执行父组件传递过来的函数 */}
      <button onClick={()=>onGetMsg(sonMsg)}>send</button>
    </div>
  )
    
}
​
function App(){
  const getMsg = (msg)=>console.log(msg)
  
  return (
    <div>
      {/* 传递父组件中的函数到子组件 */}
       <Son onGetMsg={ getMsg }/>
    </div>
  )
}

兄弟间通信(状态通信)

a传父组件,父组件传b

javascript 复制代码
// 1. 通过子传父 A -> App
// 2. 通过父传子 App -> B
​
import { useState } from "react"
​
function A ({ onGetAName }) {
  // Son组件中的数据
  const name = 'this is A name'
  return (
    <div>
      this is A compnent,
      <button onClick={() => onGetAName(name)}>send</button>
    </div>
  )
}
​
function B ({ name }) {
  return (
    <div>
      this is B compnent,
      {name}
    </div>
  )
}
​
function App () {
  const [name, setName] = useState('')
  const getAName = (name) => {
    setName(name)
  }
  return (
    <div>
      this is App
      <A onGetAName={getAName} />
      <B name={name} />
    </div>
  )
}
​
export default App

跨层通信

实现步骤:

  1. 使用 createContext方法创建一个上下文对象Ctx

  2. 在顶层组件(App)中通过 Ctx.Provider 组件提供数据

  3. 在底层组件(B)中通过 useContext 钩子函数获取消费数据

javascript 复制代码
// App -> A -> B
​
import { createContext, useContext } from "react"
​
// 1. createContext方法创建一个上下文对象
​
const MsgContext = createContext()
​
function A () {
  return (
    <div>
      this is A component
      <B />
    </div>
  )
}
​
function B () {
  // 3. 在底层组件 通过useContext钩子函数使用数据
  const msg = useContext(MsgContext)
  return (
    <div>
      this is B compnent,{msg}
    </div>
  )
}
​
function App () {
  const msg = 'this is app msg'
  return (
    <div>
      {/* 2. 在顶层组件 通过Provider组件提供数据 */}
      <MsgContext.Provider value={msg}>
        this is App
        <A />
      </MsgContext.Provider>
    </div>
  )
}
​
export default App
相关推荐
GISer_Jing9 分钟前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼38 分钟前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长1 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs1 小时前
Nginx核心架构设计
运维·前端·nginx
雪球工程师团队2 小时前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程
m0_471199632 小时前
【场景】前端怎么解决离线收银、数据同步异常等场景问题
前端·javascript
Curvatureflight2 小时前
前端性能优化实战:从3秒到300ms的加载速度提升
前端·人工智能·性能优化
用户99045017780092 小时前
ruoyi集成dmn规则引擎
前端
袋鱼不重2 小时前
AI入门知识点:什么是 AIGC、多模态、RAG、Function Call、Agent、MCP?
前端·aigc·ai编程