美文网首页
Taro 多行文本显示全部和收起

Taro 多行文本显示全部和收起

作者: blossom_6694 | 来源:发表于2019-11-23 15:52 被阅读0次

有个显示全部和收起的需求,要求超过100个字符就显示100个字符,可查看全部。
效果:


1111.jpg 222.jpg

代码:txs

import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
import classNames from 'classnames'
import asterStore from '@/store/aster_store'

interface State {
    isShow: boolean
    isShowAll: boolean
    showContent: string
}

interface IProps {
    content: string
}

export default class MoreText extends Component<IProps> {

    state: Readonly<State> = {
        isShow: false,
        isShowAll: false,
        showContent: ''
    }

    componentDidMount() {
        const { content } = this.props
        if (content.length > 100) {
            this.setState({
                isShow: true,
                showContent: content.substring(0, 100)
            })
        } else {
            this.setState({
                showContent: content
            })
        }
    }

    onClick(e: Event) {
        e.stopPropagation()
        const { isShowAll } = this.state
        const { content } = this.props

        var showContent = ''
        if (isShowAll) {
            showContent = content.substring(0, 100)
        } else {
            showContent = content
        }

        this.setState({
            isShowAll: !isShowAll,
            showContent: showContent
        })

    }

    render() {
        const { isShow, isShowAll, showContent } = this.state
        const themeColor = asterStore.theme.color

        return (
            <View className='more-text' >

                <Text className='content'>
                    {showContent}</Text>

                {isShow && !isShowAll && <Text className='dot'>...</Text>}

                {isShow && <Text className={ classNames({'padding-left-20': isShowAll})} onClick={this.onClick.bind(this)} style={{ color: themeColor }} >{isShowAll ? '收起' : '查看全部>'}</Text>}

            </View>
        );
    }
}

scss:

@import '../../styles/base.scss';

.more-text {
    margin-left: 40px;
    margin-right: 40px;

    float: left;

    line-height: 48px;
    font-size: 28px;
    color: $color-deep;

    .dot {
        padding-left: 20px;
    }

    .padding-left-20 {
        padding-left: 20px;
    }

}

相关文章

网友评论

      本文标题:Taro 多行文本显示全部和收起

      本文链接:https://www.haomeiwen.com/subject/guuhwctx.html