reactjs v18 父组件通过map生成了多个子组件如何获取这些子组件的ref并进行操作
在 React v18 中,你可以使用 useRef 钩子来获取子组件的 ref。然后,你可以通过在子组件上设置 ref 属性来引用它们。以下是一个使用 useRef 的示例:
父组件:
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const childRefs = useRef([]);
const handleClick = () => {
// 使用子组件的 ref 进行操作
childRefs.current.forEach(childRef => {
childRef.current.doSomething();
});
};
return (
<div>
{Array.from({ length: 3 }).map((_, index) => (
<ChildComponent key={index} ref={ref => childRefs.current[index] = ref} />
))}
<button onClick={handleClick}>操作子组件</button>
</div>
);
}
export default ParentComponent;
子组件:
import React, { useRef } from 'react';
const ChildComponent = React.forwardRef((props, ref) => {
const childRef = useRef();
// 暴露子组件的 ref
React.useImperativeHandle(ref, () => ({
doSomething() {
console.log('子组件执行操作');
// 在这里执行你的操作
}
}));
return <div>子组件</div>;
});
export default ChildComponent;
在上面的代码中,我们首先在父组件中创建了一个 useRef 钩子来存储子组件的 ref。然后,我们通过使用 ref 属性将子组件的 ref 传递给父组件,并在父组件中将其存储在 childRefs.current 数组中的相应索引位置。
在父组件中,我们定义了一个 handleClick 函数,在这个函数中我们可以访问子组件的 ref,并调用其中的方法(例如 doSomething)来执行操作。
在子组件中,我们使用了 forwardRef 函数来转发 ref,并使用 useImperativeHandle 钩子来定义一个可暴露给父组件的方法(例如 doSomething)。这样,父组件就可以通过子组件的 ref 来调用子组件中的方法。
这样,你就可以通过父组件的 map 函数生成多个子组件,并在需要时通过子组件的 ref 进行操作
原文地址: https://www.cveoy.top/t/topic/ibcy 著作权归作者所有。请勿转载和采集!