[英]Passing array of refs in React
I'm creating a ref array from another component , later on, I need to pass it to an inner component .我正在从另一个组件创建一个ref 数组,稍后,我需要将它传递给一个内部组件。 Passing them as props is pointless in the inner component since it returns null.
在内部组件中将它们作为 props 传递是没有意义的,因为它返回 null。 I tried forwarding an array of them, but that won't work either.
我尝试转发其中的一个数组,但这也不起作用。 I'm currently stuck at this point and I don't know how to go from here.
我目前被困在这一点上,我不知道如何从这里开始。
So the question is: What have I been doing wrong and what could be an alternative solution if mine is wrong?所以问题是:我做错了什么,如果我做错了,有什么替代解决方案? How would you guys pass multiple refs to an inner component ?
你们如何将多个引用传递给内部组件?
Parent component:父组件:
const Path: React.FC = () => {
{...}
const pathParameters = [
{ d: 'M 500 500 L 800 500', fill: 'transparent', stroke: '#f00' },
{ d: 'M 810 500 L 1105 500', fill: 'transparent', stroke: '#f00' },
{ d: 'M 1110 500 L 1410 500 L 1410 810 L 810 810', fill: 'transparent', stroke: '#f00' },
{ d: 'M 800 810 L 500 810', fill: 'transparent', stroke: '#f00' },
{ d: 'M 805 495 L 805 195', fill: 'transparent', stroke: '#000' },
{ d: 'M 805 195 L 805 495', fill: 'transparent', stroke: '#000' },
{ d: 'M 805 505 L 805 805', fill: 'transparent', stroke: '#000' },
{ d: 'M 805 805 L 805 505', fill: 'transparent', stroke: '#000' }
];
const pathRefs: RefObject<SVGPathElement>[] = [];
const paths = pathParameters.map((path, index) => {
pathRefs[index] = useRef(null);
return (
<path key={index} ref={pathRefs[index]} d={path.d} fill={path.fill} stroke={path.stroke} />
);
return (
<svg
onMouseMove={event => dispatch(updateMouseCoordinates(getMouseCoordinates(event)))}
width='1920'
height='1080'
viewBox='0 0 1920 1080'
xmlns='http://www.w3.org/2000/svg'
>
{paths}
<Knob ref={pathRefs} />
</svg>
);
};
Inner component:内部组件:
const Knob = React.forwardRef((props, ref) => {
{...}
return (
<circle
onMouseDown={() => dispatch(enableDragging())}
onMouseUp={() => dispatch(disableDragging())}
cx={knobCoordinates.x}
cy={knobCoordinates.y}
r='30'
/>
);
});
export default Knob;
What I understand from your problem is that {paths}
is not rendered when <Knob />
gets rendered so that's why your pathRefs
is a null array.我从你的问题中了解到,当
<Knob />
被渲染时, {paths}
不会被渲染,所以这就是为什么你的pathRefs
是一个空数组。 Plus the ref
attribute on a component is to specify the component's ref, not to pass info to it.另外,组件上的
ref
属性是指定组件的 ref,而不是将信息传递给它。
In my opinion, an acceptable option would be to put your pathRefs
' array in your state and update it on componentDidMount
so you'll be able to pass this.state.pathRefs
to your <Knob />
在我看来,一个可接受的选择是将你的
pathRefs
数组置于你的状态并在componentDidMount
上更新它,这样你就可以将this.state.pathRefs
传递给你的<Knob />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.