美文网首页
React 父子组件通信

React 父子组件通信

作者: cy_Wey | 来源:发表于2023-02-03 15:18 被阅读0次

    1. 父传子

    通过props传递

    // 父组件
    export default function App() {
      return <Child value="111"></Child>
    }
    // 子组件
    function Child(props) {
      return <div>我是父组件传递的value:{props.value}</div>
    }
    

    2. 子传父

    通过父组件传递函数让子组件调用

    import {useState} from 'react'
    // 父组件
    export default function App() {
      const [value,setValue] = useState(0)
      const fn = (value) => {
        setValue(value)
      }
      return (
        <>
        <div>我是子组件传递的Value:{value}</div>
        <Child fn={fn}></Child>
        </>
      )
    }
    
    // 子组件
    function Child(props) {
      const fn1 = () => {
        props.fn(123)
      }
      return (
        <button onClick={fn1}>子传父</button>
      )
    }
    

    相关文章

      网友评论

          本文标题:React 父子组件通信

          本文链接:https://www.haomeiwen.com/subject/clshhdtx.html