首页 > 解决方案 > 使用 useRef 获取更改的孩子的更新高度

问题描述

我有一个手风琴组件,我使用 useRef 来测量孩子的身高。但是我对孩子有更改内容的功能,但孩子的测量没有更新,除非我再次点击切换。

const Accordian = ({ isOpen, children }) => {
  const chilRef = useRef();
  const [childHeight, setChildHeight] = useState(0);

  useEffect(() => {
    if (isOpen) {
      const childHeight = chilRef.current && chilRef.current.scrollHeight;
      setChildHeight(childHeight);
    }
  }, [isOpen]);

  return (
    <div
      style={{
        display: isOpen ? "block" : "none"
      }}
    >
      <div ref={chilRef}>
        {children}

        <br />
        <br />
        <div>ChildHeight: {childHeight}</div>
      </div>
    </div>
  );
};

export default function App() {
  const [boxOpen, setBoxOpen] = useState(true);
  const [expandChild, setExpandChild] = useState(false);

  return (
    <div className="App">
      <button
        onClick={() => {
          setBoxOpen(prev => !prev);
        }}
      >
        Toggle box
      </button>
      <Accordian isOpen={boxOpen}>
        {expandChild ? (
          <>
            <h1>Hello CodeSandbox</h1>
            <div>This has more content</div>
            <div>More content......</div>
          </>
        ) : (
          <>
            <div>Hello</div>
            <button
              onClick={() => {
                setExpandChild(true);
              }}
            >
              Expand child
            </button>
          </>
        )}
      </Accordian>
    </div>
  );
}

https://codesandbox.io/s/jovial-rgb-vcqnz?file=/src/App.js:83-1435

每次孩子改变时,我如何获得孩子的身高?

标签: javascriptreactjs

解决方案


只需将孩子传递给钩子的依赖项。

const Accordian = ({ children }) => {
  const chilRef = useRef();
  const [childHeight, setChildHeight] = useState(0);

  useEffect(() => {
    if (children) {
      const childHeight = chilRef.current && chilRef.current.scrollHeight;
      setChildHeight(childHeight);
    }
  }, [children]);

  return (
    <div>
      <div ref={chilRef}>
        {children}

        <br />
        <br />
        <div>ChildHeight: {childHeight}</div>
      </div>
    </div>
  );
};

https://codesandbox.io/s/smoosh-hooks-u8pnt


推荐阅读