taro中多行文本的展开和隐藏

前言

taro构建的项目中实现超过5行文本自动隐藏,点击全文展开文本,点击收起隐藏文本。

具体效果如下
只显示5行文本多余隐藏,点击全文展开隐藏文本
在这里插入图片描述
点击收起隐藏文本
在这里插入图片描述

代码实现

import Taro, {
    
     Component } from "@tarojs/taro";
import {
    
     Text, View } from "@tarojs/components";

import classNames from "classnames";

import "./index.scss";
const isH5 = process.env.TARO_ENV === "h5";
class Ellipsis extends Component {
    
    
  state = {
    
    
    showAll: true,
    showFoldBtn: false
  };

  componentDidMount() {
    
    
    setTimeout(() => {
    
    
      this.handleTextHight();
    }, 50); //防止dom没有加载完成
  }

  handleTextHight = () => {
    
    
  // 注意Taro.createSelectorQuery().in()参数,要区分h5和小程序,
  //小程序为this.$scope,h5为this
    const query = Taro.createSelectorQuery().in(isH5 ? this : this.$scope);
    query.select(".dynamic-detail-content-text").fields({
    
    
      size: true
    });
    query.exec(res => {
    
    
      if (!res[0]) return;
      const lineHeight = 20;
      if (lineHeight * 5 < res[0].height) {
    
    
        this.setState({
    
    
          showAll: false,
          showFoldBtn: true
        });
      }
    });
  };

  handleFoldText = () => {
    
    
    this.setState({
    
    
      showAll: !this.state.showAll
    });
  };

  render() {
    
    
    const {
    
     showAll, showFoldBtn } = this.state;
    return (
      <View>
        <Text
          className={
    
    classNames("dynamic-detail-content-text", {
    
    
            "dynamic-detail-content-text-less": !showAll
          })}
        >
          新华社喀布尔分社报道员看到,16日上午,当地银行、大型商场仍关门歇业,街道上车辆和行人较少,电力供应、电话和网络信号不稳定。在喀布尔市内,仍能听到零星枪声。
          16日,塔利班已经控制了喀布尔市全部地区。喀布尔机场外有大量试图离开的阿富汗民众,载有外国外交人员的直升机密集起降,喀布尔机场仍比较混乱。俄罗斯卫星通讯社报道说,美军当天向闯入机场跑道的一些阿富汗人开枪,造成至少3人死亡。
          塔利班方面同日表示,允许聚集在喀布尔机场的阿富汗民众回家,同时承诺其行动不会伤及平民。
          分管政治事务的塔利班领导人阿卜杜勒·加尼·巴拉达尔15日晚表示,塔利班近期取得的胜利超出预料,塔利班下一步将面临确保安全稳定和给国民带来福祉等考验。
        </Text>
        {
    
    showFoldBtn && (
          <Text
            className="operate-text-btn"
            onClick={
    
    () => {
    
    
              this.handleFoldText();
            }}
          >
            {
    
    showAll ? "收起" : "全文"}
          </Text>
        )}
      </View>
    );
  }
}

export default Ellipsis ;

样式代码

.dynamic-detail-content-text {
    
    
  font-size: 30px;
  font-weight: 400;
  color: #ccc;
}

.dynamic-detail-content-text-less {
    
    
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  word-wrap: break-word;
  white-space: normal !important;
  -webkit-line-clamp: 5; 
  /*! autoprefixer: ignore next */
  -webkit-box-orient: vertical;
}

.operate-text-btn {
    
    
  color: #ff7f00;
  margin-left: 4px;
  font-size: 30px;
}

猜你喜欢

转载自blog.csdn.net/weixin_43398820/article/details/119788750