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
相关推荐
SUPER52662 小时前
FastApi项目启动失败 got an unexpected keyword argument ‘loop_factory‘
java·服务器·前端
sanx182 小时前
专业电竞体育数据与系统解决方案
前端·数据库·apache·数据库开发·时序数据库
你的人类朋友4 小时前
【Node】认识一下Node.js 中的 VM 模块
前端·后端·node.js
Cosolar4 小时前
FunASR 前端语音识别代码解析
前端·面试·github
@大迁世界7 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
芭拉拉小魔仙7 小时前
Vue项目中如何实现表格选中数据的 Excel 导出
前端·vue.js·excel
jump_jump7 小时前
妙用 localeCompare 获取汉字拼音首字母
前端·javascript·浏览器
U.2 SSD8 小时前
Echarts单轴坐标系散点图
前端·javascript·echarts
不做无法实现的梦~8 小时前
jetson刷系统之后没有浏览器--解决办法
开发语言·javascript·ecmascript
德育处主任Pro8 小时前
前端玩转大模型,DeepSeek-R1 蒸馏 Llama 模型的 Bedrock 部署
前端·llama