react native Text实现限制行数,尾部直接截断。直接在下一行加省略号。
效果如图:
//超过三行就在底部加上省略号
用传统的方法只能实现在尾部加省略号,不过现在新版的RN,ellipsizeMode 属性配上
numberOfLines属性 也能实现这样的效果。不过对于老版的RN就无能为力了。刚好用的老版RN又要实现这样的效果就查资料然后想了想,然后就实现了一个这样的效果,废话不多说,上干货。
import React, { Component } from 'react';
import {
View,
Text,
Dimensions,
TouchableOpacity,
StyleSheet,
} from 'react-native';
const devicesWidth=Dimensions.get('window').width;
class MyText extends Component {
constructor(props) {
super(props);
this.state={
height:0,
tag:0,
};
}
textOnLayout(e){
const layout = e.nativeEvent.layout;
if(layout.height>60){ //行高是20然后把text的高度设置为60就能保证行数控制在3行了
this.refs.text.setNativeProps({
style:{
height:60,
width:devicesWidth-74,
}
});
this.setState({
tag:1,
});
}
}
render() {
return(
<View >
<Text
ref="text"
style={styles.text}
onLayout={this.textOnLayout.bind(this)}
>
{this.props.text}
</Text>
{this.state.tag===0?(<View></View>):(<Text style={styles.text1}>......</Text>)}
</View>
);}
}
const styles = StyleSheet.create({
text: {
fontSize:15,
lineHeight:20,
color: '#323232',
width:devicesWidth-74,
},
text1: {
fontSize:15,
lineHeight:20,
color: '#323232',
},
});
module.exports=MyText;