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
相关推荐
蓝胖子的多啦A梦31 分钟前
ElementUI表格错位修复技巧
前端·css·vue.js·el-table表格错位
QQRRRRW36 分钟前
Tailwind+VScode (Vite + React + TypeScript) 原理与实践
vscode·react.js·typescript
_OP_CHEN43 分钟前
前端开发实战深度解析:(一)认识前端和 HTML 与开发环境的搭建
前端·vscode·html·web开发·前端开发
xiAo_Ju1 小时前
iOS一个Fancy UI的Tricky实现
前端·ios
H***99761 小时前
Vue深度学习实战
前端·javascript·vue.js
toooooop82 小时前
Vuex 中 state、mutations 和 actions 的原理和写法
前端·javascript·uni-app
y***86692 小时前
前端CSS-in-JS方案
前端·javascript·css
暖木生晖2 小时前
APIs之WEB API的基本认知是什么?
前端·dom·dom树·web apis
华仔啊2 小时前
你真的懂递归吗?没那么复杂,但也没那么简单
前端·javascript
火星数据-Tina2 小时前
低成本搭建体育数据中台:一套 API 如何同时支撑比分网与 App?
java·前端·websocket