hook 中useRef获取子组件内容 forwardRef,useImperativeHandle,

Warning:Function components cannot be given refs

 报错说明:

      子组件不使用forwardRef、useImperativeHandle 那么在父组件中,通过childRef拿到的current就为null,并且还会报错

 解决:

函数式组件中没有实例!!

子组件中:

     在子组件中设置一个值,在父组件修改

import React, { useState, forwardRef, useImperativeHandle } from "react"

function Child(props, ref) {
    const [age, setAge] = useState(122)
    useImperativeHandle(ref, () => {

    // 返回的是要暴露的东西
        return {
            age,
            setAge

        }
    })
    return <div>
        Child
        <p>age is {age} </p>
    </div>
}

export default forwardRef(Child)

父组件:

     子组件没有暴露的时候 childRef.current  值为null,说明没有实例

import React, { useEffect, useRef } from 'react'
import Child from './Child'

export default function Index() {
    // 创建一个Ref 
    const childRef = useRef(null)

    const changeAge = () => {
        console.log(childRef)
        const { age, setAge } = childRef.current
        setAge(age + 1)
    }

    return <div>
       
        <button onClick={changeAge}>更改子组件的年龄</button>
        <Child ref={childRef} />

    </div>


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过使用ReactforwardRefuseImperativeHandle来实现组件事件代码调用父组件方法的功能。具体步骤如下: 1.在父组件创建一个React ref,并将其传递给组件: ```jsx import React, { useRef } from 'react';import ChildComponent from './ChildComponent'; function ParentComponent() { const childRef = useRef(null); function parentMethod() { console.log('This is a method in the parent component.'); } return ( <div> <ChildComponent ref={childRef} parentMethod={parentMethod} /> </div> ); } export default ParentComponent; ``` 2.在组件使用forwardRef来承接父组件传入的ref节点,并将其以参数的形式传给节点: ```jsx import React, { forwardRef } from 'react'; const ChildComponent = forwardRef((props, ref) => { // 组件的方法 function childMethod() { console.log('This is a method in the child component.'); } // 将组件的方法和父组件的方法绑定到refuseImperativeHandle(ref, () => ({ childMethod: childMethod, parentMethod: props.parentMethod })); return ( <div> <button onClick={props.parentMethod}>Call Parent Method</button> </div> ); }); export default ChildComponent; ``` 3.在组件使用useImperativeHandle来绑定组件的方法和父组件的方法到ref上,这样就可以在组件通过ref调用父组件的方法了。 ```jsx import React, { forwardRef, useImperativeHandle } from 'react'; const ChildComponent = forwardRef((props, ref) => { // 组件的方法 function childMethod() { console.log('This is a method in the child component.'); } // 将组件的方法和父组件的方法绑定到refuseImperativeHandle(ref, () => ({ childMethod: childMethod, parentMethod: props.parentMethod })); return ( <div> <button onClick={props.parentMethod}>Call Parent Method</button> </div> ); }); export default ChildComponent; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值