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
相关推荐
zwjapple4 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
像风一样自由20206 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
伍哥的传说6 小时前
React 各颜色转换方法、颜色值换算工具HEX、RGB/RGBA、HSL/HSLA、HSV、CMYK
深度学习·神经网络·react.js
aiprtem7 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊7 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术7 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing7 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止8 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall8 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴8 小时前
简单入门Python装饰器
前端·python