使用useRef计算孩子的总宽度

问题描述 投票:1回答:1

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

reactjs react-hooks
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.