Реагируйте на общую ширину детей, используя useRef - PullRequest
1 голос
/ 22 апреля 2019

Как рассчитать общую ширину детей с помощью React's useRef?Чего я хочу добиться, так это получить доступ к собственности каждого ребенка, включая ref.Обратите внимание, что каждый компонент Child имеет разную ширину.У меня есть коды и поле здесь .

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 голосов
/ 23 апреля 2019

Я смог ответить на это.Тем не менее, я не уверен, что передача ссылки на опору - это хороший подход.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;
...