Я смог ответить на это.Тем не менее, я не уверен, что передача ссылки на опору - это хороший подход.Codesandbox здесь .
import React, { useState, useRef, useEffect } from "react";
const ComputeWidth = ({ children }) => {
const [totalWidth, setTotalWidth] = useState(0);
const els = React.Children.map(children, useRef);
const newChildren = React.Children.map(children, (element, i) => {
const newProps = {
...element.props,
additionalProp: 1234,
el: els[i]
};
return <element.type ref={els[i]} {...newProps} />;
});
useEffect(() => {
setTotalWidth(
newChildren.reduce(
(pv, cv) => pv.ref.current.offsetWidth + cv.ref.current.offsetWidth
)
);
}, []);
return (
<div>
{newChildren}
<div>Width is {totalWidth}</div>
</div>
);
};
export const Child = ({ label, el }) => (
<div ref={el} style={{ display: "inline" }}>
{label}
</div>
);
export default ComputeWidth;