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
相关推荐
人工智能训练师1 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny071 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy2 小时前
css的基本知识
前端·css
昔人'3 小时前
css `lh`单位
前端·css
前端君3 小时前
实现最大异步并发执行队列
javascript
Nan_Shu_6144 小时前
Web前端面试题(2)
前端
知识分享小能手4 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队5 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光6 小时前
css之一个元素可以同时应用多个动画效果
前端·css
萌萌哒草头将军6 小时前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite