簡體   English   中英

如何檢查反應功能組件中的div是否溢出

[英]How to check if a div is overflowing in react functional component

我試圖找出一個 div 是否溢出了文本,如果有,則show more鏈接。 我找到了這個 stackoverflow 答案來檢查 div 是否溢出 根據這個答案,我需要實現一個函數,該函數可以訪問相關元素的樣式並進行一些檢查以查看它是否溢出。 如何訪問元素的樣式。 我嘗試了兩種方法

1.使用參考

import React from "react";
import "./styles.css";

export default function App(props) {
  const [showMore, setShowMore] = React.useState(false);
  const onClick = () => {
    setShowMore(!showMore);
  };

  const checkOverflow = () => {
    const el = ref.current;
    const curOverflow = el.style.overflow;

    if ( !curOverflow || curOverflow === "visible" )
        el.style.overflow = "hidden";

    const isOverflowing = el.clientWidth < el.scrollWidth 
        || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isOverflowing;
  };

  const ref = React.createRef();

  return (
    <>
      <div ref={ref} className={showMore ? "container-nowrap" : "container"}>
        {props.text}
      </div>
      {(checkOverflow()) && <span className="link" onClick={onClick}>
        {showMore ? "show less" : "show more"}
      </span>}
    </>
  )
}

2.使用前向引用

子組件

export const App = React.forwardRef((props, ref) => {
  const [showMore, setShowMore] = React.useState(false);
  const onClick = () => {
    setShowMore(!showMore);
  };

  const checkOverflow = () => {
    const el = ref.current;
    const curOverflow = el.style.overflow;

    if (!curOverflow || curOverflow === "visible") el.style.overflow = "hidden";

    const isOverflowing =
      el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isOverflowing;
  };

  return (
    <>
      <div ref={ref} className={showMore ? "container-nowrap" : "container"}>
        {props.text}
      </div>
      {checkOverflow() && (
        <span className="link" onClick={onClick}>
          {showMore ? "show less" : "show more"}
        </span>
      )}
    </>
  );
});

父組件

import React from "react";
import ReactDOM from "react-dom";

import { App } from "./App";

const rootElement = document.getElementById("root");
const ref = React.createRef();
ReactDOM.render(
  <React.StrictMode>
    <App
      ref={ref}
      text="Start editing to see some magic happen! Click show more to expand and show less to collapse the text"
    />
  </React.StrictMode>,
  rootElement
);

但是我在這兩種方法中都遇到了以下錯誤- Cannot read property 'style' of null 我究竟做錯了什么? 我怎樣才能達到我想要的?

正如 Jamie Dixon 在評論中建議的那樣,我使用useLayoutEffect掛鈎將showLink設置為 true。 這是代碼

零件

import React from "react";
import "./styles.css";

export default function App(props) {
  const ref = React.createRef();
  const [showMore, setShowMore] = React.useState(false);
  const [showLink, setShowLink] = React.useState(false);

  React.useLayoutEffect(() => {
    if (ref.current.clientWidth < ref.current.scrollWidth) {
      setShowLink(true);
    }
  }, [ref]);

  const onClickMore = () => {
    setShowMore(!showMore);
  };

  return (
    <div>
      <div ref={ref} className={showMore ? "" : "container"}>
        {props.text}
      </div>
      {showLink && (
        <span className="link more" onClick={onClickMore}>
          {showMore ? "show less" : "show more"}
        </span>
      )}
    </div>
  );
}

CSS

.container {
  overflow-x: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 200px;
}

.link {
  text-decoration: underline;
  cursor: pointer;
  color: #0d6aa8;
}

我們可以創建一個自定義鈎子來知道我們是否有溢出。

import * as React from 'react';

const useIsOverflow = (ref, isVerticalOverflow, callback) => {
  const [isOverflow, setIsOverflow] = React.useState(undefined);

  React.useLayoutEffect(() => {
    const { current } = ref;
    const { clientWidth, scrollWidth, clientHeight, scrollHeight } = current;

    const trigger = () => {
      const hasOverflow = isVerticalOverflow ? scrollHeight > clientHeight : scrollWidth > clientWidth;

      setIsOverflow(hasOverflow);

      if (callback) callback(hasOverflow);
    };

    if (current) {
      trigger();
    }
  }, [callback, ref, isVerticalOverflow]);

  return isOverflow;
};

export default useIsOverflow;

只需檢查您的組件

import * as React from 'react';

import { useIsOverflow } from './useIsOverflow';

const App = () => {
  const ref = React.useRef();
  const isOverflow = useIsOverflow(ref);

  console.log(isOverflow);
  // true

  return (
    <div style={{ overflow: 'auto', height: '100px' }} ref={ref}>
      <div style={{ height: '200px' }}>Hello React</div>
    </div>
  );
};

感謝 Robin Wieruch 的精彩文章https://www.robinwieruch.de/react-custom-hook-check-if-overflow/

使用 TS 和 Hooks 的解決方案

創建您的自定義鈎子:

import React from 'react'

interface OverflowY {
  ref: React.RefObject<HTMLDivElement>
  isOverflowY: boolean
}

export const useOverflowY = (
  callback?: (hasOverflow: boolean) => void
): OverflowY => {
  const [isOverflowY, setIsOverflowY] = React.useState(false)
  const ref = React.useRef<HTMLDivElement>(null)

  React.useLayoutEffect(() => {
    const { current } = ref

    if (current) {
      const hasOverflowY = current.scrollHeight > window.innerHeight
      // RHS of assignment could be current.scrollHeight > current.clientWidth
      setIsOverflowY(hasOverflowY)
      callback?.(hasOverflowY)
    }
  }, [callback, ref])

  return { ref, isOverflowY }
}

使用你的鈎子:

const { ref, isOverflowY } = useOverflowY()
//...
<Box ref={ref}>
...code

根據需要導入文件並根據需要更新代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM