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 = useRef<any>(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到此这篇关于React通过ref获取子组件的数据和方法的文章就介绍到这了,更多相关React ref获取子组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
采用React编写小程序的Remax框架的编译流程解析(推荐)
这篇文章主要介绍了采用React编写小程序的Remax框架的编译流程解析(推荐),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-04-04
使用VScode 插件debugger for chrome 调试react源码的方法
这篇文章主要介绍了使用VScode 插件debugger for chrome 调试react源码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-09-09
在React中使用Antd上传并读取Excel文件的详细步骤
在React中使用Antd组件库来上传并读取Excel文件,可以结合antd的Upload组件和xlsx库来实现,以下是一个详细的步骤和示例代码,展示如何在React应用中实现这一功能,感兴趣的小伙伴跟着小编一起来看看吧2025-01-01


最新评论