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
相关推荐
申阳2 分钟前
Day 6:04. 基于Nuxt开发博客项目-LOGO生成以及ICON图标引入
前端·后端·程序员
中国lanwp14 分钟前
npm中@your-company:registry 和 registry 的区别
前端·npm·node.js
Bacon16 分钟前
Electron 应用商店:开箱即用工具集成方案
前端·github
行走的陀螺仪17 分钟前
uni-app + Vue3 实现折叠文本(超出省略 + 展开收起)
前端·javascript·css·uni-app·vue3
冴羽20 分钟前
JavaScript 异步循环踩坑指南
前端·javascript·node.js
jump68021 分钟前
commonjs 和 ES Module
前端
旧曲重听143 分钟前
前端需要掌握多少Node.js?
前端·node.js
Mr.Jessy44 分钟前
Web APIs 学习第四天:DOM事件进阶
开发语言·前端·javascript·学习·ecmascript
云枫晖1 小时前
前端工程化实战:手把手教你构建项目脚手架
前端·前端工程化
醉方休1 小时前
开发一个完整的Electron应用程序
前端·javascript·electron