React通过ref获取子组件的数据和方法

发布时间:2026/9/26 10:06:42
React通过ref获取子组件的数据和方法 一、函数式组件父组件1) ref必须传值, 否则childRef拿不到子组件的数据和方法注意: 不一定使用app组件, 其他的任何父组件都可以import ./App.css; import React, { useEffect, useRef } from react; import RefToGetChild from ./components/RefToGetChild; import _ from lodash; const App: React.FC () { const childRef useRefany(null); useEffect(() { console.log(_.get(childRef, current)); }, [_.get(childRef, current)]); return ( div RefToGetChild ref{childRef} message{子组件: say hello} / button onClick{() { const child _.get(childRef, current); const buttonDom child.buttonRef.current buttonDom?.click(); }}父组件: trigger child button/button button onClick{() { const child _.get(childRef, current); child?.onTest(); }}父组件: 使用子组件的onTest方法/button div父组件: 子组件的data {JSON.stringify(_.get(childRef, current.data))}/div /div ); }; export default App;子组件1) forwardRef作用: 封装组件, 直接将ref参数加在props后面(也可以不使用, 自己props定义一下ref需要传参, 父组件一样传ref就行)2) useImperativeHandle作用和vue3的defineExpose一样, 存储需要暴露给父组件让其获取的数据和函数import { forwardRef, useEffect, useImperativeHandle, useRef, useState, } from react; const RefToGetChild forwardRef((props:{message:string;}, ref) { const [data, setData] useState({}); const buttonRef useRef(null); useEffect(() { setTimeout(() { const obj { a: 1, b: 2, c: 3, d: Array.from({ length: 10 }, (_, i) ({ id: i })), }; setData(obj); }, 1000); }, []); const sayHello () { console.log(hello); }; const onTest () { console.log(test) } useImperativeHandle(ref, () ({ data, buttonRef, onTest, })); return ( div button ref{buttonRef} onClick{sayHello} {props.message} /button /div ); }); export default RefToGetChild二、class组件父组件 给子组件传onRef函数普通一个子组件获取子组件的方法很常见就不赘述了写一个获取列表的子组件内部方法或变量的示例import { PureComponent, Fragment } from react; class AttachmentList extends PureComponent { constructor(props) { super(props); this.state { arr: [{ id: 1 }], }; this.aiAuditRefMap React.createRef(); } render() { const { arr [], resetState } this.state; Fragment {arr.map(record { Child onRef{ref { try { if (!this.aiAuditRefMap.current) { this.aiAuditRefMap.current {}; } if (record.id) { this.aiAuditRefMap.current[record.id] ref; } } catch (err) { console.log(err, err); } }} {...resetState} /; })} /Fragment; } }子组件在componentDidMount、componentDidUpdate生命周期使用this.props.onRef(this)将子组件的instance传给组件关键代码componentDidMount() { const { onRef } this.props; if (onRef) { onRef(this); // 传递这个onRef函数父组件可以使用这个组件的方法 } } componentDidUpdate() { const { onRef } this.props; if (onRef) { onRef(this); // 传递这个onRef函数父组件可以使用这个组件的方法 } }

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询