Reactjs React使用useRef计算儿童的总宽度

Reactjs React使用useRef计算儿童的总宽度,reactjs,react-hooks,Reactjs,React Hooks,如何使用React的useRef计算孩子们的总宽度?我想要实现的是访问每个孩子的属性,包括ref。请注意,每个孩子的组件具有不同的宽度。我有一个密码沙盒 我能够回答这个问题。然而,我不确定将裁判传给道具是否是一个好方法。代码沙盒 import React from "react"; const ComputeWidth = ({ children }) => { let totalWidth = 0; const newChildren = React.Children.map

如何使用React的useRef计算孩子们的总宽度?我想要实现的是访问每个孩子的属性,包括ref。请注意,每个孩子的组件具有不同的宽度。我有一个密码沙盒


我能够回答这个问题。然而,我不确定将裁判传给道具是否是一个好方法。代码沙盒

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;

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;