美文网首页React
react-hook 父子传值

react-hook 父子传值

作者: jack_rofer | 来源:发表于2021-08-06 00:02 被阅读0次

    redux 来传值应该是最好的吧,还有useContext,待更。。。

    一.父传子(简单-属性传值)

    // 父组件
    import { useState } from 'react'
    import ChildCom from './learnUseforward'
    const FatherCom = () => {
        const [count, setCount] = useState(123456)
        return (
            <div>
                <ChildCom data={ count }/>
            </div>
        )
    }
    
    export default FatherCom
    
    // 子组件
    function ChildCom (props) {
        return (
            <div>
               { props.data }     
            </div>
        )
    }
    
    export default ChildCom
    

    二.子传父(使用useRef)

    // 父组件
    import { useRef } from 'react'
    import { Button} from 'antd'
    import ChildCom from './learnUseforward'
    const FatherCom = () => {
        const childRef = useRef(null)
        const handleGetChildData = () => {
            const data = childRef.current.getFromData()
            console.log('data', data)
        }
        return (
            <div>
                <ChildCom ref={ childRef }/>           
                <Button onClick={() => handleGetChildData()}>我要获取子组件的数据</Button>
            </div>
        )
    }
    
    
    export default FatherCom
    
    // 子组件
    import { useState, forwardRef, useImperativeHandle } from 'react'
    import { Button } from 'antd'
    function ChildCom (props, ref) {
        const [formValue, setFormValue] = useState({name: 'ky', age: 18})
        useImperativeHandle(ref, ()=>({
            getFromData: ()=> {
                return formValue
            }
        }))
        return (
            <div>
                我是from组件          
            </div>
        )
    }
    
    ChildCom = forwardRef(ChildCom)
    //这里用forwardRef包裹住了,LearnUseforward必须以函数声明,不能是变量声明
    
    export default ChildCom
    

    相关文章

      网友评论

        本文标题:react-hook 父子传值

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