MutiRowText.js
2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Created by yangxia on 11/10/18.
* 字数超过自指定行数后显示更多
*/
import React, {Component} from 'react';
import {StyleSheet, Text,} from 'react-native';
import PropTypes from 'prop-types';
export default class MutiRowText extends Component {
static propTypes = {
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>
<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>
</Text>
);
}
}
const styles = StyleSheet.create({
text: {
fontSize: 14,
color:'#000000',
}
});