简体   繁体   中英

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 . Passing them as props is pointless in the inner component since it returns 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. Plus the ref attribute on a component is to specify the component's ref, not to pass info to it.

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 />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM