【问题标题】:Why clientHeight or offsetHeight not available on ref element on toggled div in React component with useRef hook为什么在带有 useRef 钩子的 React 组件中切换 div 上的 ref 元素上不可用 clientHeight 或 offsetHeight
【发布时间】:2021-04-19 08:57:41
【问题描述】:

我有一个显示和隐藏一些内容的 React 组件。

这里是working example

const Collapse = ({ children }: Props) => {
  const [isOpen, setIsOpen] = useState(false);
  const [height, setHeight] = useState<number | undefined>(0);
  const toggledHeight = isOpen ? height : 0;
  const myRef = useRef<HTMLDivElement>(null);
  const toggle = () => setIsOpen(!isOpen);

  useEffect(() => {
    setHeight(myRef.current?.clientHeight);
  }, [myRef]);

  // useLayoutEffect(() => {
  //   setHeight(myRef.current?.clientHeight);
  // }, []);

  return (
    <React.Fragment>
      <div
        ref={myRef}
        className={`content ${isOpen ? "isOpen" : ""}`}
        style={{ height: `${toggledHeight}px` }}
      >
        {children}
        {console.log(height)}
        {console.log(myRef)}
      </div>
      <button type="button" onClick={toggle}>
        <span>Toggle content</span>
      </button>
    </React.Fragment>
  );
};

export default Collapse;

我想在显示和隐藏内容时创建一个 css height 过渡。

为什么myRef.current?.offsetHeightmyRef.current?.clientHeight 不可用并且始终0

【问题讨论】:

    标签: css reactjs use-effect use-state


    【解决方案1】:

    在样式中,您传递的是动态高度。我认为它没有进入像素。所以你需要从

    style={{ height: ${height+"px"} }}

    【讨论】:

      【解决方案2】:

      看起来你从一开始就告诉它为 0 :)

      无需寻找确切的高度数字,只需动画max-height

      我已经成功地为你制作了这样的动画代码:

      const Collapse = ({ children }: Props) => {
        const [isOpen, setIsOpen] = useState(false);
        const toggle = () => {
          setIsOpen(!isOpen);
        };
      
        return (
          <>
            <div
              style={{
                maxHeight: isOpen ? '1000px' : '0px',
                transition: 'max-height 1s ease-in-out',
              }}
            >
              {children}
            </div>
            <button type="button" onClick={toggle}>
              <span>Toggle content</span>
            </button>
          </>
        );
      };
      

      【讨论】:

      • 我不想将 maxHeight 设置为固定值。我真的很好奇为什么clientHeight 在我切换的ref 元素上不可用...
      猜你喜欢
      • 2023-03-26
      • 2014-05-05
      • 2022-10-12
      • 1970-01-01
      • 2021-05-05
      • 2020-01-29
      • 2022-01-08
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多