react文本溢出hover气泡显示全部文本——JS判断文本溢出

需求:
在文本溢出的时候,显示气泡

JS相关知识

// target js元素
const containerLength = target.width; //当前容器的宽度
const textLength = target.scrollWidth; //  当前文字(包括省略部分)的宽度

文本溢出的css, 如超过100px显示...

.ellipis {
    display: inline-block;
    vertical-align: middle;
     auto;
    max- 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

react组件计算,是否溢出

import React, { Component } from "react";
import { Popover } from "antd"

export default class PopoverEllipsis extends  Component{
  constructor(props) {
    super(props);

    this.state = {
      showPopover: false
    };
  }

  componentDidMount() {
    this.validShowPopover();
  }

  validShowPopover = () => {
    const { scrollWidth, clientWidth } = this.children;
    this.setState({
      showPopover: scrollWidth > clientWidth
    })
  }
  
  refChildren = (ref) => {
    this.children = ref;
  }

  renderChildren() {
    return (
      React.cloneElement(
        this.props.children, {
          ref: this.refChildren
        }
      )
    )
  }

  render() {
    let {
      children,
      ...other
    } = this.props;
    const {
      showPopover
    } = this.state;

    if (showPopover) {
      return (
        <Popover
          title={null}
          content={null}
          placement="top"
          {...other}
        >
          { this.renderChildren() }
        </Popover>
      )
    }

    return this.renderChildren()
  }
}


原文地址:https://www.cnblogs.com/qiqi715/p/11775748.html