转载:http://blog.csdn.net/jan8705_/article/details/52279533
原理:组件初始化时不设置Text控件的numberOfLines属性,测量一下组件高度(最大高度),然后在设置numberOfLines属性,再次测量一下组件高度(最小高度),若最大高度大与最小高度,表示需要显示“展开”。
- /*eslintnew-cap:["error",{"capIsNew":false}]*/
- importReact,{
- Component,
- PropTypes,
- }from'react';
- import{View,Image,StyleSheet,Animated,Text}from'react-native';
- exportdefaultclassCollapsibleTextextendsComponent{
- staticpropTypes={
- style:Text.propTypes.style,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> expandTextStyle:Text.propTypes.style,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> numberOfLines:PropTypes.number
- }
- constructor(props){
- super(props);
- this.state={
- /**文本是否展开*/
- expanded:true,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> numberOfLines:null,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> /**展开收起文字是否处于显示状态*/
- showExpandText:false,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> expandText:'展开',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> /**是否处于测量阶段*/
- measureFlag:true
- this.numberOfLines=props.numberOfLines;
- /**文本是否需要展开收起功能:(实际文字内容是否超出numberOfLines限制)*/
- this.needExpand=true;
- this.measureFlag=true;
- }
- _onTextLayout(event){
- if(this.measureFlag){
- if(this.state.expanded){
- this.maxHeight=event.nativeEvent.layout.height;
- this.setState({expanded:false,numberOfLines:this.numberOfLines});
- }else{
- this.mixHeight=event.nativeEvent.layout.height;
- if(this.mixHeight==this.maxHeight){
- this.needExpand=false;
- this.needExpand=true;
- this.setState({showExpandText:true})
- this.measureFlag=false;
- _onPressExpand(){
- if(!this.state.expanded){
- this.setState({numberOfLines:null,expandText:'收起',expanded:true})
- }else{
- this.setState({numberOfLines:this.numberOfLines,expandText:'展开',expanded:false})
- render(){
- const{numberOfLines,onLayout,expandTextStyle,...rest}=this.props;
- letexpandText=this.state.showExpandText?(
- <Text
- style={[this.props.style,styles.expandText,expandTextStyle]}
- onPress={this._onPressExpand.bind(this)}>
- {this.state.expandText}</Text>
- ):null;
- return(
- <View>
- <Text
- numberOfLines={this.state.numberOfLines}
- onLayout={this._onTextLayout.bind(this)}
- {...rest}
- >
- {this.props.children}
- </Text>
- {expandText}
- </View>
- );
- conststyles=StyleSheet.create({
- expandText:{
- color:'blue',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> marginTop:0
- });