创建 Child 组件
Child.tsx
import { forwardRef, useImperativeHandle } from "react";
type ChildComponentProps = {
props1: string;
};
type ChildComponentRef = {
foo: () => void;
bar: () => void;
};
const ChildComponent = forwardRef<ChildComponentRef, ChildComponentProps>((props, ref) => {
const foo = () => {};
const bar = () => {};
useImperativeHandle(ref, () => ({
foo,
bar
}))
return (<div></div>);
})
export default ChildComponent;
创建 Parent 组件
- 通过 useRef 创建一个数组去存放组件 ref;
- 通过循环的下标将 ref 绑定到数组中;
Parent.tsx
import { useCallback, useRef, useState } from 'react';
import ChildComponent, { ChildComponentRef } from './Child';
type ParentProps = {};
type ItemData = {
key: number;
title: string;
};
const Parent: React.FC<ParentProps> = (props) => {
const listRefs = useRef<Array<ChildComponentRef | null>>([]);
const [list, setList] = useState<Array<ItemData>>([
{ key: 1, title: 'title1' },
{ key: 2, title: 'title2' },
{ key: 3, title: 'title3' },
]);
const showListRefs = useCallback(() => {
console.log(listRefs);
}, [list]);
return (
<div>
<button onClick={showListRefs}>获取 ref</button>
{list.map((item, index) => (
<ChildComponent
key={item.key}
props1={item.title}
// 这里将 ref 绑定到 listRefs 上
ref={(ref) => (listRefs.current[index] = ref)}
/>
))}
</div>
);
};
export default Parent;