React@16.x(30)useImperativeHandle

目录

1,介绍

介绍 ref时提到,ref 不能作用于函数组件,所以有了 ref 转发

举例:

js 复制代码
function Child(props, ref) {
    return <h1 ref={ref}>child</h1>;
}

const ChildWrap = React.forwardRef(Child);

export default function App() {
    const refChild = useRef();
    return (
        <>
            <ChildWrap ref={refChild}></ChildWrap>
            <button
                onClick={() => {
                    console.log(refChild.current);
                }}
            >
                获取Child组件
            </button>
        </>
    );
}

useImperativeHandle 的作用:在 ref 转发的前提下,为了更方便的在函数组件中使用 ref

2,使用

其他代码不变,只对子组件做如下修改:

js 复制代码
function Child(props, ref) {
    useImperativeHandle(
        ref,
        () => {
            return 123; // 相当于 ref.current = 123
        },
        []
    );
    // 此时 h1 上的 ref 失效。
    return <h1 ref={ref}>child</h1>;
}

同样的,依赖项不变,该HOOK的回调函数不会再次执行。

此时在父组件中获取的 refChild.current 就是 123。

所以如果想通过父组件调用子组件的一些方法,可以将这些方法放到 useImperativeHandle 的第2个参数中即可:

js 复制代码
function Child(props, ref) {
    useImperativeHandle(
        ref,
        () => {
            return {
                method1() {
                    console.log("method1");
                },
                method2() {
                    console.log("method2");
                },
            };
        },
        []
    );
    return <h1>child</h1>;
}

父组件调用:refChild.current.method1()


以上。

相关推荐
前进的李工1 分钟前
智能Agent实战指南:记忆组件嵌入技巧(记忆)
开发语言·前端·javascript·python·langchain·agent
西洼工作室4 分钟前
B站登录流程全解析:RSA+极验验证
前端·python·极验
十有八七24 分钟前
AI Agent的“骨架”之争:四种Harness设计哲学深度解构
前端·人工智能
卡次卡次127 分钟前
14.2:详细补充:子进程会复制什么
前端·python·php
泽_浪里白条29 分钟前
superset 踩过的坑之嵌入式 Dashboard 数据筛选
前端·后端
IOT.FIVE.NO.130 分钟前
Codex Skill 内部结构解析:从 SKILL.md 到 scripts、references、assets
前端·javascript·人工智能·笔记·html
PILIPALAPENG40 分钟前
第4周 Day 2:多步推理 Agent——让 Agent 学会"先想再干"
前端·人工智能·python
LPieces2 小时前
从零实现 AI 流式对话:SSE + Node.js 完整指南
前端
Crystal3282 小时前
【终极指南】前端方面解决 uni-app APP 端 SSE 流式请求被缓冲拦截、无法实时渲染的问题
android·前端·ai编程