react中子传父信息

思路是:

在父组件定义一个函数接受参数,接收的参数用于接收子组件的信息,把函数传给子组件,子组件调用父亲传来的函数并把要告诉父亲的话传到函数中,就实现了子传父消息

复制代码
import { useState } from 'react'

import { useRef } from 'react'
// import './App.css'




function Son({onGetSonMsg}) {
const mesgForFa = "子传父亲的消息"
  return(
    <div>这是儿子组件
       <button onClick={()=>onGetSonMsg(mesgForFa)}>告诉父亲</button>
    </div>
  )
}



function App() {
  const [count, setCount] = useState(0)
const inputRef = useRef(null)
const sonMsg = (msg)=>{
    console.log(msg);
    
}


  return (
    <>
      
      <Son onGetSonMsg={sonMsg}>
      </Son>
    </>
  )
}

export default App
相关推荐
|晴 天|18 小时前
Vue 3 + TypeScript + Element Plus 博客系统开发总结与思考
前端·vue.js·typescript
猫32819 小时前
v-cloak
前端·javascript·vue.js
旷世奇才李先生19 小时前
Vue 3\+Vite\+Pinia实战:企业级前端项目架构设计
前端·javascript·vue.js
SoaringHeart20 小时前
Flutter进阶:用OverlayEntry 实现所有弹窗效果
前端·flutter
IT_陈寒1 天前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
herinspace1 天前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
小码哥_常1 天前
从MVC到MVI:一文吃透架构模式进化史
前端
嗷o嗷o1 天前
Android BLE 的 notify 和 indicate 到底有什么区别
前端
豹哥学前端1 天前
别再背“var 提升,let/const 不提升”了:揭开暂时性死区的真实面目
前端·面试
lar_slw1 天前
k8s部署前端项目
前端·容器·kubernetes