react中使用forwardRef获取子组件中的节点以及子组件的方法(useImperativeHandle的使用)

1.forwardRef的使用

javascript 复制代码
import { forwardRef, useRef } from "react"


const Son = forwardRef((props, ref)=> {
    return (
        <input type="text" ref={ref} id="kannoId"/>
    )
})

function ForwardRef() {
    const sonRef = useRef(null)
    const showRef = () => {
        console.log("sonRef", sonRef.current,document.getElementById('kannoId'));
        sonRef.current.focus()
        // document.getElementById('kannoId').focus()
    }
    return (
        <div>
            我是父组件
            <button onClick={showRef}>点击</button>
            <Son ref={sonRef} />
        </div>
    )
}

export default ForwardRef

说明:获取子组件中的节点可以通过子传父、js获取节点方式、forwardRef

2.useImperativeHandle的使用

javascript 复制代码
import { forwardRef, useRef,useImperativeHandle } from "react"


const Son = forwardRef((props, ref)=> {
    function kanno(){
        console.log("36除了6还是6");
    }
    useImperativeHandle(ref,()=>{ // 使用钩子函数暴露子组件中的方法
        return {
            kanno
        }
    })
    return (
        <input type="text" id="kannoId"/>
    )
})

function ForwardRef() {
    const sonRef = useRef(null)
    const showRef = () => {
        console.log("sonRef", sonRef.current,document.getElementById('kannoId'));
        sonRef.current.kanno()
        // sonRef.current.focus()
        // document.getElementById('kannoId').focus()
    }
    return (
        <div>
            我是父组件
            <button onClick={showRef}>点击</button>
            <Son ref={sonRef} />
        </div>
    )
}

export default ForwardRef
相关推荐
和平宇宙13 小时前
AI笔记005. hermes-DeepSeek V4 Pro, 128K上下文引发的探索
前端·人工智能·笔记
IT_陈寒13 小时前
Redis持久化这个坑,我爬了一整天才出来
前端·人工智能·后端
naildingding13 小时前
3-ts接口 Interface
前端·typescript
mONESY13 小时前
JavaScript 栈、队列、数组与链表核心知识点总结
javascript·面试
小小前端仔LC14 小时前
Node.js + LangChain + React:搭建个人知识库(六)- “吃什么”项目实战:从700+菜谱入库到Taro H5端JSON渲染
前端·后端
ZengLiangYi14 小时前
TypeScript 项目配置:tsconfig、ESM、路径别名
javascript·typescript·aigc
晓131314 小时前
【Cocos Creator 3.x】篇——第二章 入门
前端·javascript·游戏引擎
想要成为糕糕手14 小时前
前端必修课:JavaScript 数组与数据结构底层逻辑全解析
javascript·数据结构·面试
程序员黑豆14 小时前
AI全栈开发之Java:怎么配置Java环境变量
前端·后端·ai编程
xiaofeichaichai14 小时前
React Hooks
前端·javascript·react.js