1. 程式人生 > >React Native 指定文字行數,超出行數顯示更多

React Native 指定文字行數,超出行數顯示更多

純屬於工具類,簡單的說一下原理,
1、在不給text設定numberOfLines的時候計算出text的高度。
2、給text一個特定的numberOfLines,然後再次計算高度。
3、比較兩次獲取的高度,如果第二次獲取的高度<最大高度,說明需要換行,回撥給頁面。
4、頁面通過回撥知道需不需要顯示“載入更多操作”。

用法:

<MutiRowText
                    style={{flex:1}}
                    numLines={this.state.numLines}
                    onMutiCallBack={()
=>
{ if(!this.state.isMuti){ this.setState({ isMuti:true, }); } }} > {你的文字資訊} </MutiRowText>

然後改變state改變行數:

if(this.state.numLines===null){ this.setState({ //2行顯示 numLines:2, }); }else{ //顯示全部 this.setState({ numLines:null
, }); }

MutiRowText.js:

/**
 * Created by YASIN on 2017/8/21.
 * 字數超過自指定行數後顯示更多
 */
import React, {Component, PropTypes}from 'react';
import {
    View,
    Text,
    StyleSheet,
}from 'react-native';

import * as ScreenUtils from '../utils/ScreenUtil';
import Colors from '../../app/config/colors';
export default class MutiRowText extends Component {
    static propTypes = {
        style: Text.propTypes.style,
        numLines: PropTypes.any,
        onMutiCallBack: PropTypes.func,
        allowFontScaling: PropTypes.bool,
    }
    static defaultProps = {
        allowFontScaling: false,
    }
    // 構造
    constructor(props) {
        super(props);
        // 初始狀態
        this.state = {
            numLines: null,
            maxHeight: null,
            opacity: 0,
        };
    }

    shouldComponentUpdate(newProps, newState) {
        return this.state.numLines !== newProps.numLines;
    }

    componentWillReceiveProps(nextProps) {
        if (this.state.numLines !== nextProps.numLines) {
            this.setState({
                numLines: nextProps.numLines
            });
        }
    }

    render() {
        return (
            <Text
                style={[styles.text,this.props.style,{opacity:this.state.opacity}]}
                allowFontScaling={this.props.allowFontScaling}
                numberOfLines={this.state.numLines}
                onLayout={(event)=>{
                    let height = event.nativeEvent.layout.height;
                    //第一次測量view的最大高度
                    if(this.state.maxHeight===null&&this.props.numLines){
                        this.state.maxHeight=height;
                        this.setState({
                            numLines:this.props.numLines,
                            opacity:1,
                        });
                    //第二次當測量的最大高度>設定行數後的高度的時候,回撥需要換行。
                    }else if(this.props.numLines){
                        if(this.state.maxHeight>height){
                            if(this.props.onMutiCallBack){this.props.onMutiCallBack()}
                        }
                    }
                }}
            >
                {this.props.children}
            </Text>
        );
    }
}
const styles = StyleSheet.create({
    text: {
        fontSize: ScreenUtils.scaleSize(28),
        color: Colors.text_dark_grey,
    }
});