【React】组件通信 - 子传父

组件通信 - 子传父

核心思路

  • 在子组件中调用父组件中的函数并传递参数

示例

import { useState } from "react"

function Son({ onGetSonMsg }) {
  const sonMsg = "this is son msg"
  return (
    <div>
      this is son,
      <button onClick={() => onGetSonMsg(sonMsg)}>sendMsg</button>
    </div>
  )
}

function App() {
  const [msg, setMsg] = useState('')
  
  const getMsg = (msg) => {
    setMsg(msg)
  }

  return (
    <div>
      this is App, {msg}
      <Son onGetSonMsg={getMsg}/>
    </div>
  );
} 
...
posted @ 2024-09-02 01:41  505donkey  阅读(15)  评论(0)    收藏  举报