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
相关推荐
light blue bird15 分钟前
主子端台二分法任务汇总组件
前端·数据库·.net·桌面端winform
不可能的是1 小时前
Claude Code 子 Agent 机制全解:怎么跑起来、怎么被管理、怎么互不干扰
javascript
jeffwang1 小时前
我做了个让 AI 看屏幕跑测试的工具,因为 Playwright 测不了我的 Flutter Web
前端
HSunR2 小时前
dify 搭建ai作业批改流
开发语言·前端·javascript
代码不加糖2 小时前
2026 跨境电商独立站实战:从 0 到 1 搭建高转化 SaaS 商城(附源码)
开发语言·前端·javascript
亲亲小宝宝鸭2 小时前
拖一拖控件,拖出个问卷(低代码平台)
前端·低代码
江南十四行2 小时前
ReAct Agent 基本理论与项目实战(一)
前端·react.js·前端框架
We་ct3 小时前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划
小呆呆6663 小时前
Codex 穷鬼大救星
前端·人工智能·后端
当时只道寻常4 小时前
Vue3 + IntersectionObserver 实现高性能图片懒加载
前端