1.安装依赖:
npm install rn-expandable-text --save
2.组件内容
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet,
} from 'react-native';
import ExpandableText from 'rn-expandable-text';
import PropTypes from 'prop-types';
export default class expandableText extends Component {
expandView = () => {
const spread = this.props.expandText ? this.props.expandText : '展开';
const spreadStyle = this.props.spreadStyle ? this.props.spreadStyle : styles.spread;
return (
<View style={spreadStyle}>
<Text style={this.props.spreadFont}>{spread}</Text>
</View>
);
};
unexpandView = () => {
const retract = this.props.unexpandText ? this.props.unexpandText : '收起';
const retractStyle = this.props.retractStyle ? this.props.retractStyle : styles.spread;
return (
<View style={retractStyle}>
<Text style={this.props.retractFont}>{retract}</Text>
</View>
);
}
// 内容扩展时的回调
onExpand = () => {
if (this.props.onExpand) {
this.props.onExpand();
}
}
// 内容折叠时的回调
onCollapse = () => {
if (this.props.onCollapse) {
this.props.onCollapse();
}
}
render() {
const content = this.props.content ? this.props.content : '内容为空';
const expandableStyle = this.props.expandableText ? this.props.expandableText : styles.expandableText;
return (
<View>
<ExpandableText
numberOfLines={this.props.numberOfLines} // 内容的最大行数
style={expandableStyle} // 文本的总体样式布局
unexpandView={this.unexpandView} // 展开时的文本 ‘收起’
expandView={this.expandView} // 未展开时的文本 ‘展开’
onExpand={this.onExpand} // 内容扩展时的回调
onCollapse={this.onCollapse} // 内容折叠时的回调
animationDuration={20} // 展开或折叠动画的持续时间(ms)
>
<Text style={this.props.contentStyle}>{content}</Text>
</ExpandableText>
</View>
);
}
}
expandableText.propTypes = {
numberOfLines: PropTypes.number, // 内容的最大行数
style: PropTypes.string, // 文本的总体样式布局
onExpand: PropTypes.func, // 内容扩展时的回调
onCollapse: PropTypes.func, // 内容折叠时的回调
expandText: PropTypes.string, // 未展开时的文本内容
spreadStyle: PropTypes.string, // 设置未展开时的文本的位置
spreadFont: PropTypes.string, // 设置未展开时的文本内容的样式
unexpandText: PropTypes.string, // 展开时的文本内容
retractStyle: PropTypes.string, // 展开时的文本的位置
retractFont: PropTypes.string, // 设置展开时的文本内容的样式
contentStyle: PropTypes.string, // 折叠文本内容的样式
expandableStyle: PropTypes.string, // 文本的总体样式布局
animationDuration: PropTypes.number, // 展开或折叠动画的持续时间(ms)
};
expandableText.propsDefault = {
numberOfLines: 5,
animationDuration: 20,
};
const styles = StyleSheet.create({
expandableText: {
marginHorizontal: 20,
},
spread: {
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
marginRight: 20,
marginTop: 5,
},
});
完成后就是下边的样式