react文本溢出hover氣泡顯示全部文本——JS判斷文本溢出


需求:
在文本溢出的時候,顯示氣泡

JS相關知識

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

文本溢出的css, 如超過100px顯示...

.ellipis {
    display: inline-block;
    vertical-align: middle;
    width: auto;
    max-width: 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()
  }
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM