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
相关推荐
whuhewei10 小时前
为什么客户端不存在跨域问题
前端·安全
妮妮喔妮10 小时前
supabase的webhook报错
开发语言·前端·javascript
qq_120840937110 小时前
Three.js 大场景分块加载实战:从全量渲染到可视集调度
开发语言·javascript·数码相机
yivifu11 小时前
手搓HTML双行夹批效果
前端·html·html双行夹注
奔跑的卡卡11 小时前
Web开发与AI融合-第一篇:Web开发与AI融合的时代序幕
前端·人工智能
IT_陈寒11 小时前
Redis批量删除的大坑,差点让我加班到天亮
前端·人工智能·后端
帆张芳显12 小时前
智表ZCELL产品V3.6 版发布,新增系统预置右键菜单操作、页签栏操作等功能
前端·canva可画·excel插件
漂流瓶jz12 小时前
运行时vs编译时:CSS in JS四种主流方案介绍和对比
前端·javascript·css
Asmewill12 小时前
uv包管理命令
前端
发现一只大呆瓜12 小时前
深入浅出 Tree Shaking:Rollup 是如何“摇”掉死代码的?
前端·性能优化·vite