繁体   English   中英

React 显示 Material-UI 工具提示仅适用于带有省略号的文本

[英]React show Material-UI Tooltip only for text that has ellipsis

寻找一种方法让 material-ui 的工具提示在文本被省略号(溢出)截断时才展开表格单元格中的文本。

目前在我的表中,我有一个这样的单元格:

<TableCell className={classes.descriptionCell}>{row.description}</TableCell>

我对 descriptionCell 的样式是这样的:

    descriptionCell: {
        whiteSpace: 'nowrap',
        maxWidth: '200px',
        overflow: 'hidden',
        textOverflow: 'ellipsis'
    }

这使得文本按照我希望在该表中的方式运行,但我希望能够 hover 并在工具提示中查看它的 rest,最好是 Material-UI 的内置工具提示组件。

我知道这里有一个 package https://www.npmjs.com/package/react-ellipsis-with-tooltip应该这样做,但它使用引导工具提示,而不是材料 UI。

离开@benjamin.keen 的回答。 这是一个独立的功能组件,它只是他使用钩子执行比较功能的答案的扩展。

import React, { useRef, useEffect, useState } from 'react';
import Tooltip from '@material-ui/core/Tooltip';
const OverflowTip = props => {
  // Create Ref
  const textElementRef = useRef();

  const compareSize = () => {
    const compare =
      textElementRef.current.scrollWidth > textElementRef.current.clientWidth;
    console.log('compare: ', compare);
    setHover(compare);
  };

  // compare once and add resize listener on "componentDidMount"
  useEffect(() => {
    compareSize();
    window.addEventListener('resize', compareSize);
  }, []);

  // remove resize listener again on "componentWillUnmount"
  useEffect(() => () => {
    window.removeEventListener('resize', compareSize);
  }, []);

  // Define state and function to update the value
  const [hoverStatus, setHover] = useState(false);

  return (
    <Tooltip
      title={props.value}
      interactive
      disableHoverListener={!hoverStatus}
      style={{fontSize: '2em'}}
    >
      <div
        ref={textElementRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        }}
      >
        {props.someLongText}
      </div>
    </Tooltip>
  );
};

export default OverflowTip;

请在下面找到代码和框 - https://codesandbox.io/s/material-demo-p2omr

我在这里使用 ref 来获取 TableCell DOM 节点,然后比较 scrollWidth 和 clientWidth 以确定是否必须显示 Tooltip。(这是基于此处的答案)

我已将“rowref”(具有 ref 的属性)和“open”(禁用/启用工具提示)添加为行的新属性。 我不知道您的数据来自哪里,但我假设您可以将这些属性添加到行中。

还有一件事要注意,我只是设置“disableHoverListener”道具来禁用 tooltip 。 还有其他道具 - "disableFocusListener" 和 "disableTouchListener" ,如果你想使用它们。 更多信息在这里

希望这对你有用。 如果您对代码有任何疑问,请告诉我。

我今天遇到了同样的问题,@vijay-menon 的回答非常有帮助。 这是一个简单的独立组件,用于同一件事:

import React, { Component } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

class OverflowTip extends Component {
    constructor(props) {
        super(props);
        this.state = {
            overflowed: false
        };
        this.textElement = React.createRef();
    }

    componentDidMount () {
        this.setState({
            isOverflowed: this.textElement.current.scrollWidth > this.textElement.current.clientWidth
        });
    }

    render () {
        const { isOverflowed } = this.state;
        return (
            <Tooltip
                title={this.props.children}
                disableHoverListener={!isOverflowed}>
                <div
                    ref={this.textElement}
                    style={{
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                    }}>
                    {this.props.children}
                </div>
            </Tooltip>
        );
    }
}

用法示例:

<OverflowTip>
      some long text here that may get truncated based on space
</OverflowTip>

一个麻烦是如果元素的空间在页面中动态变化(例如页面调整大小或动态 DOM 变化),它不会确认新空间并重新计算它是否溢出。

其他工具提示库(如 Tippy)有一个方法,当尝试打开工具提示时会触发该方法。 这是进行溢出检查的理想场所,因为它始终有效,无论文本元素的 DOM 宽度是否已更改。 不幸的是,使用 Material UI 提供的 API 来做到这一点比较麻烦。

基于 benjamin.keen 的回答,这是他的代码的功能版本:

import React, { useRef, useState, useEffect } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

const OverflowTip = ({ children }) => {
  const [isOverflowed, setIsOverflow] = useState(false);
  const textElementRef = useRef();
  useEffect(() => {
    setIsOverflow(textElementRef.current.scrollWidth > textElementRef.current.clientWidth);
  }, []);
  return (
    <Tooltip title={children} disableHoverListener={!isOverflowed}>
      <div
        ref={textElementRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {children}
      </div>
    </Tooltip>
  );
};

我不认为你需要进入任何副作用钩子。 最上面的帖子建议在 window 上放置一个事件监听器,它会在每次鼠标移动事件时触发。 我们可以只定义一些回调并将它们传递给onMouseEnteronMouseLeave

import React, { useState, MouseEvent } from "react";
import Tooltip, { TooltipProps } from "@mui/material/Tooltip";

export const OverflowTooltip = ({ children, ...props }: TooltipProps) => {
  const [tooltipEnabled, setTooltipEnabled] = useState(false);

  const handleShouldShow = ({ currentTarget }: MouseEvent<Element>) => {
    if (currentTarget.scrollWidth > currentTarget.clientWidth) {
      setTooltipEnabled(true);
    }
  };

  const hideTooltip = () => setTooltipEnabled(false);

  return (
    <Tooltip
      onMouseEnter={handleShouldShow}
      onMouseLeave={hideTooltip}
      disableHoverListener={!tooltipEnabled}
      {...props}
    >
      <div
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {children}
      </div>
      {children}
    </Tooltip>
  );
};

基于@Dheeraj 的回答——这与他的组件非常接近,但在类型脚本版本中,更有意义的道具名称:

import React, { useRef, useEffect, useState } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

interface Props {
  tooltip: string;
  text: string;
}

const OverflowTooltip = (props: Props) => {

  const textElementRef = useRef<HTMLInputElement | null>(null);

  const compareSize = () => {
    const compare =
      textElementRef.current.scrollWidth > textElementRef.current.clientWidth;
    setHover(compare);
  };

  useEffect(() => {
    compareSize();
    window.addEventListener('resize', compareSize);
  }, []);

  useEffect(() => () => {
    window.removeEventListener('resize', compareSize);
  }, []);

  const [hoverStatus, setHover] = useState(false);

  return (
    <Tooltip
      title={props.tooltip}
      interactive
      disableHoverListener={!hoverStatus}
    >
      <div
        ref={textElementRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {props.text}
      </div>
    </Tooltip>
  );
};

export default OverflowTooltip;

我们像这样使用它:

<OverflowTooltip 
    tooltip={'tooltip message here'}
    text={'very long text here'}
/>

如果有人需要 TypScript 版本:

import { Tooltip, Typography, TypographyProps } from "@mui/material";
import { FC, ReactChild, useEffect, useRef, useState } from "react";

export interface OverflowTypograpyProps extends TypographyProps {
  children: ReactChild;
}

export const OverflowTypograpy: FC<OverflowTypograpyProps> = ({
  children,
  ...props
}) => {
  const ref = useRef<HTMLSpanElement>(null);
  const [tooltipEnabled, setTooltipEnabled] = useState(false);

  useEffect(() => {
    const compareSize = () => {
      if (ref.current) {
        const compare = ref.current.scrollWidth > ref.current.clientWidth;

        setTooltipEnabled(compare);
      }
    };
    compareSize();
    window.addEventListener("resize", compareSize);
    return () => window.removeEventListener("resize", compareSize);
  }, []);

  return (
    <Tooltip title={children} disableHoverListener={!tooltipEnabled}>
      <Typography
        ref={ref}
        noWrap
        overflow="hidden"
        textOverflow="ellipsis"
        {...props}
      >
        {children}
      </Typography>
    </Tooltip>
  );
};

定义文本是否溢出的方法在接受的答案中存在缺陷。 由于scrollWidth<\/code>和clientWidth<\/code>返回四舍五入的整数值,当它们之间的差异很小时,我们将得到相等的值,并且 tooltip 将不起作用。 问题是省略号也算作clientWidth<\/code> ,所以当我们只有一个或 tho 个字符溢出时,我们会看到省略号,但scrollWidth<\/code>和clientWidth<\/code>会相等。 以下是对我scrollWidth<\/code>的解决方案,用于确定具有分数精度的scrollWidth<\/code>和clientWidth<\/code>并解决了此问题:

import React, { useRef, useState, useEffect } from 'react';
import { Tooltip } from '@material-ui/core';

const OverflowTooltip = ({ children }) => {
    const textElementRef = useRef();
    
    const checkOverflow = () => {
        // Using getBoundingClientRect, instead of scrollWidth and clientWidth, to get width with fractional accuracy
        const clientWidth = textElementRef.current.getBoundingClientRect().width

        textElementRef.current.style.overflow = 'visible';
        const contentWidth = textElementRef.current.getBoundingClientRect().width
        textElementRef.current.style.overflow = 'hidden';

        setIsOverflow(contentWidth > clientWidth);
    }
    
    useEffect(() => {
        checkOverflow();
        window.addEventListener('resize', checkOverflow)
        return () => {
            window.removeEventListener('resize', checkOverflow)
        }
    }, []);
    
    const [isOverflowed, setIsOverflow] = useState(false);
    
  return (  
    <Tooltip title={children} disableHoverListener={!isOverflowed}>       
      <span ref={textElementRef}
            style={{
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
            }}
        >
            {children}
      </span>
    </Tooltip>
  );
};
export default OverflowTooltip

如果您只想在内容溢出时显示工具提示,这将起作用。

需要useEffect()<\/code>是因为ref.current<\/code>最初为 null,但是当组件挂载时,它会被设置,您可以基于它获取 html 元素。

interface MyInterface {
    content: Content;
}

export const MyComponent: React.FC<MyInterface> = ({ content }) => {
const ref = useRef(null);

const [showTooltip, setShowTooltip] = useState(false);

useEffect(() => {
    if (!ref.current) return;

    const div = ref.current as HTMLDivElement;
    const isOverflow = div.offsetWidth < div.scrollWidth;
    setShowTooltip(isOverflow);
}, []);

const renderContent = () => (
    <div ref={ref}>
        content
    </div>
);

return (
    <>
        {ref.current && showTooltip ? (
            <Tooltip title={content.value}>
                {renderContent()}
            </Tooltip>
        ) : (
            renderContent()
        )}
    </>
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM