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
相关推荐
吃好睡好便好7 分钟前
在Matlab中用sphere( )函数绘制球面图
开发语言·前端·javascript·学习·算法·matlab·信息可视化
黑贝是条狗8 分钟前
注册表破解chrome,edge阻止浏览器连接本地websocket
前端·javascript·数据库
UXbot11 分钟前
AI 原型工具对比(2026):从文字描述到完整 App 界面的 5 款主流平台评测
android·前端·ios·交互·软件构建
ZC跨境爬虫14 分钟前
跟着 MDN 学 HTML day_53:(深入理解 XPathResult 接口)
前端·javascript·ui·html·音视频
摸鱼仙人~16 分钟前
html-anything 仓库全面介绍
前端·html
之歆20 分钟前
DAY_24JavaScript 面向对象深度全解:Object、构造函数与 this 系统指南(上)
开发语言·前端·javascript·原型模式
梦梦代码精23 分钟前
开源智能体平台 BuildingAI 深度解析:Monorepo 架构、MCP 集成及 GPT-Image-2 接入实测
前端·人工智能·后端·gpt·开源·github
Asurplus26 分钟前
【VUE】17、使用JSEncrypt对数据加解密
javascript·vue.js·jsencrypt·rsa
fanzhonghong26 分钟前
javaWeb开发之前端实战(Tlias案例-部门管理)
前端·后端·web·前后端分离
广州华水科技29 分钟前
2026年高口碑GNSS变形监测一体机推荐:提升水库安全解决方案
前端