如何使用React的useRef
计算孩子的总宽度?我想要实现的是访问每个孩子的财产,包括ref
。请注意,每个Child
的组件都有不同的宽度。我有一个codeandbox here。
import React from "react";
const ComputeWidth = ({ children }) => {
let totalWidth = 0;
const newChildren = React.Children.map(children, element => {
const newProps = {
...element.props,
additionalProp: 1234
};
// I WANT TO ACCESS CHILD'S WIDTH HERE
// element.ref is null
// totalWidth += element.ref.current.offsetWidth???
return React.cloneElement(element, newProps);
});
return <div>{newChildren}</div>;
};
export const Child = ({ label }) => label;
export default ComputeWidth;
我能够回答这个问题。但是,我不确定是否将参考文献传递给道具是一种很好的方法。 Codesandbox here。
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;