React组件如何暴露自身的方法

一、研究背景

最近遇到一个如何暴露React组件自身方法的问题。在某些时候,我们需要调用某个组件内部的方法以实现某个功能,因此我们需要了解如何暴露组件内部API的方法。

二、实践过程

本文主要介绍React组件暴露子组件API的方法,以下是实践过程:

ref

props

静态属性方法

React.forwardRef

useImperativeHandle

等可以实现组件暴露自身API,部分API示例代码如下:

javascript 复制代码
import React, {useImperativeHandle} from "react";
import ReactDOM from "react-dom/client";

class App extends React.Component {
    constructor(props) {
        super(props);
        // 创建一个ref存储textInput的DOM元素
        this.forwardButtonRef = React.createRef();
        this.homeRef = React.createRef();
        // 控制台输出:{ current: null },展开:current: <div>....,因为引用值被后续的ref值覆盖而改变
        console.log("forwardButtonRef-", this.forwardButtonRef);
    }

    // ref回調函數
    childRefCallback = (el) => {
        console.log("App的childRefCallback-", el);
        this.childInputRef = el;
    };

    componentDidMount() {
        // 在此或者更晚的方法获取ref(组件挂载后)
        console.log(
            "Child-",
            this.childInputRef,
            "forwardRef-button-",
            this.forwardButtonRef,
            "homeRef-",
            this.homeRef
        );
        // 调用子组件向外暴露的方法
        this.childInputRef.handleChildClick()
        this.forwardButtonRef.current.handleForwardRefClick()
        this.homeRef.current.handleHomeClick()
    }

    render() {
        return (
            <div>
                <h1>组件暴露自身API的方法</h1>
                {/* ref回调函数 */}
                <Child inputRef={this.childRefCallback}/>
                {/* 转发ref,在父组件获取子组件的ref */}
                <ForwardRefButton ref={this.forwardButtonRef}>
                    <span>ForwardRef</span>
                </ForwardRefButton>
                <Home ref={this.homeRef}/>
            </div>
        );
    }
}


// 使用forwardRef轉發ref
const ForwardRefButton = React.forwardRef((props, fdRef) => {

    const handleForwardRefClick = () => {
        console.log("ForwardRefButton的handleForwardRefClick方法");
    };

    // 向外暴露方法,讓父組件訪問子組件中的方法
    useImperativeHandle(fdRef, () => ({
      handleForwardRefClick,
    }));

    return (
        <button ref={fdRef} className="frButton">
            {props.children}
        </button>
    );
});

function Child(props) {
    function handleChildClick() {
        console.log("Child的handleChildClick方法");
    }

    // 函数式组件向外暴露自身方法
    useImperativeHandle(props.inputRef, () => ({
        handleChildClick,
    }));

    return <input ref={props.inputRef}/>;
}

class Home extends React.Component {
    // 类組件會自動向外暴露該組件的配置信息
    handleHomeClick = () => {
        console.log("Home的handleHomeClick方法");
    };

    render() {
        return <div onClick={this.handleHomeClick}>Home</div>;
    }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App/>);

下面是实践的效果,明显发现已经获取到组件内部的方法,如下图2-1所示。

图 2-1

三、参考文献

javascript - React 组件暴露自身 API 的方法 - 个人文章 - SegmentFault 思否

react+typescript 父组件主动获取子组件内暴露的方法或属性 - 天高任鸟飞吧 - 博客园 (cnblogs.com)

相关推荐
丷丩5 分钟前
MapLibre GL JS第21课:绘制GeoJSON点图标、注记
前端·javascript·gis·mapbox·maplibre gl js
LCG元16 分钟前
现代Web应用高可用架构设计与性能调优实战
前端·wpf
丷丩37 分钟前
MapLibre GL JS第20课:更新GeoJSON多边形
前端·javascript·gis·mapbox·maplibre gl js
swipe40 分钟前
DeepAgents middleware 工程实战:把复杂 Agent 的运行时基建交给可组合中间件
前端·面试·llm
前端环境观察室1 小时前
别让 Agent 浏览器任务无限重试:失败分类、RetryPolicy 与人工复核
前端
喵个咪1 小时前
Headless 后端实践:基于Go的企业级多栈管理系统脚手架
前端·vue.js·react.js
m0_738120721 小时前
渗透测试基础——黑盒测试下的Web漏洞挖掘与利用解析(一)
服务器·前端·网络·安全·php
Larcher2 小时前
JS 变量提升:代码没动,为什么执行顺序就变了?
前端·javascript·前端框架
yingyima3 小时前
MySQL 事件调度器速查:核心语法与实战代码
前端
GISer_Jing3 小时前
Claude Code多Agent架构深度剖析
前端·人工智能·架构·自动化