使用useRef反应计算孩子的总宽度

时间:2019-04-22 12:28:42

标签: reactjs react-hooks

如何使用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;

1 个答案:

答案 0 :(得分:0)

我能够回答这个问题。但是,我不确定将引用传递给道具是否是一个好方法。 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;