React-多行文本的展开收起-组件化

922 阅读1分钟

关键样式动态添加类名

.hiddenText {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
}

组件tsx

import { View, Image } from '@tarojs/components';
import { useEffect, useRef, useState } from 'react';

import BottomArrow from '@/assets/bottomArrow.png';
import RightArrow from '@/assets/rightArrow.png';

import styles from './index.module.less';

const JuryDesc: React.FC<{
  /** 文本内容 */
  introduce: string;
}> = ({ introduce }) => {
  const descRef = useRef<any>();

    /** 是否展开 */
  const [isExpanded, setIsExpanded] = useState<boolean>(false);
  /** 是否需要展开按钮 */
  const [needExpandBtn, setNeedExpandBtn] = useState<boolean>(false);

  useEffect(() => {
  /** 组件加载完成,ref加载完成,初始状态判断。 */
    setNeedExpandBtn(
      descRef?.current?.scrollHeight > descRef?.current?.clientHeight,
    );
  }, []);

  return (
    <View className={styles.desc}>
      <View
        className={`${styles.content} ${!isExpanded ? styles.hiddenText : ''}`}
        ref={descRef}
      >
        {introduce}
      </View>
      {needExpandBtn && (
        <View
          className={styles.iconBox}
          onClick={() => setIsExpanded(!isExpanded)}
        >
          <Image
            src={isExpanded ? BottomArrow : RightArrow}
            className={styles.icon}
          />
        </View>
      )}
    </View>
  );
};

export default JuryDesc;

完整less

.desc {
  font-size: 12px * 2;
  color: #355d3d;
  line-height: 22px * 2;
  background: rgba(212, 236, 229, 0.12);
  border-radius: 4px;
  padding: 12px * 2;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;

  .content {
    word-break: break-all;
    white-space: pre-wrap;
    width: 90%;
  }

  .hiddenText {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
  }

  .iconBox {
    width: 14px * 2;
    height: 14px * 2;
    margin-bottom: 3px * 2;
    flex: 0 0 auto;

    .icon {
      width: 100%;
      height: 100%;
    }
  }
}

效果图

image.png

image.png

未超出4行文本效果

image.png

参考博客 金皮卡的个人博客