react组件间通信

1.父组件向子组件通信

复制代码
import {  useState } from 'react';
function Button(props){
  return(
    <div>{props.name}</div>
  )
}
function App() {
  const msg=useState('神雕侠侣')
  return (
    <div className="App">
      <Button name={msg}></Button>
    </div>
  );
}

export default App;
复制代码

2.子组件向父组件通信

复制代码
import {  useState } from 'react';
function Button({getsonData}){
  const msg='这是子组件传过来的'
  return(
    <div>
      {getsonData && <button  onClick={()=>{getsonData(msg) }}>子传父</button>}
    
    </div>
  )
}
function App() {
  const [msg,setMsg]=useState('')
  const getsonData=(msg)=>{
    console.log('msg',msg)
    setMsg(msg)
  }
  return (
    <div className="App">
      <Button  getsonData={getsonData}> </Button>
      <div>{msg}</div>
    </div>
  );
}

export default App;
复制代码

3.context机制跨层传递数据 

 

 

  <msgContext.Provider value={msg}>
      这是主页面
     <A></A>
  </msgContext.Provider>   必须用value
复制代码
import { createContext, useContext } from 'react';
// 1.createContext创建一个上下文对象
const msgContext=createContext()
function A(){
  return(
    <div>
      这是A组件
    <B></B>
    </div>
  )
}
function B(){
  const msg=useContext(msgContext)
  return(
    // 3.在底层组件通过useContext钩子函数使用数据
    <div>
    这是B组件{msg}
    </div>
  )
}
function App() {
const msg='this is msg'
  return (
    // 2.在顶层组件通过provider创建数据
    <div className="App" >
      <msgContext.Provider value={msg}>
      这是主页面
     <A></A>
      </msgContext.Provider>
    
    </div>
  );
}

export default App;
复制代码
posted @   小闫的姑娘  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
历史上的今天:
2022-11-10 圆圈由小变大的动画效果
点击右上角即可分享
微信分享提示