思路是:
在父组件定义一个函数接受参数,接收的参数用于接收子组件的信息,把函数传给子组件,子组件调用父亲传来的函数并把要告诉父亲的话传到函数中,就实现了子传父消息
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