taro微信小程序简单实现文本展开收起

该文章展示了一个使用Taro框架编写的LineEllipsis组件,该组件用于处理文本溢出时的显示,支持点击展开和收起。文章通过组件的状态管理和生命周期方法实现了文字的动态显示,当文字高度超过设定阈值时,显示展开按钮。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

import Taro from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { ITouchEvent } from '@tarojs/components/types/common';
import _ from 'lodash';
import './index.scss';

interface ILineEllipsis {
  text: string;
}

class LineEllipsis extends Taro.Component<ILineEllipsis> {
  disabled = false;

  state = {
    isExpansioned: false,
    overflow: false
  };

  init = () => {
    Taro.nextTick(() => {
      const query = Taro.createSelectorQuery().in(this.$scope);
      query.select(`#text`).boundingClientRect();
      query.exec(rect => {
        const height = _.get(rect, '0.height', 0);
        this.disabled = !(height > 30);
        this.setState({
          overflow: height > 30
        });
      });
    });
  };

  componentDidMount() {
    this.init();
  }

  componentWillReceiveProps() {
    this.init();
  }

  handleExpend = (e?: ITouchEvent) => {
    e && e.stopPropagation();
    this.setState({
      overflow: false,
      isExpansioned: true
    });
  };

  handleHide = (e?: ITouchEvent) => {
    e && e.stopPropagation();
    this.setState({
      overflow: true,
      isExpansioned: false
    });
  };

  toggle = () => {
    const { isExpansioned } = this.state;
    if (this.disabled) return;
    if (isExpansioned) {
      this.handleHide();
    } else {
      this.handleExpend();
    }
  };

  render() {
    const { text } = this.props;
    const { overflow, isExpansioned } = this.state;

    return (
      <View
        id="wrap"
        style={{
          position: 'relative',
          color: '#999999',
          overflow: overflow ? 'hidden' : 'unset',
          height: overflow ? '16px' : 'unset',
          lineHeight: overflow ? '16px' : 'unset'
        }}>
        <View id="text" onClick={this.toggle}>
          {text}
          {!overflow && isExpansioned && (
            <Text className="expansion-btn" onClick={this.handleHide}>
              收起
            </Text>
          )}
        </View>
        {overflow && (
          <Text
            className="expansion-btn"
            onClick={this.handleExpend}
            style={{ position: 'absolute', top: '0', right: '0', background: '#fff' }}>
            ...展开
          </Text>
        )}
      </View>
    );
  }
}

export default LineEllipsis;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值