You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native评论组件Read More文本展开动画实现咨询

React Native 评论组件文本展开动画实现方案

直接用numberOfLines做动画行不通,因为它是离散的整数属性,Animated 需要连续数值生成过渡效果,强行绑定会导致无法计算目标值(出现NaN)。换用容器高度过渡动画的方案更靠谱,具体实现步骤如下:


核心思路

通过两个隐藏的文本组件分别测量:

  1. 文本完全展开的真实高度
  2. 文本折叠为3行时的高度
    然后用Animated.Value控制实际文本容器的高度,实现平滑的展开/收起过渡。

完整代码示例

import React, { useState, useRef, useEffect } from 'react';
import { View, Text, TouchableOpacity, Animated, StyleSheet } from 'react-native';

const ReviewComment = ({ reviewComment }) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [fullTextHeight, setFullTextHeight] = useState(0);
  const [collapsedHeight, setCollapsedHeight] = useState(0);
  const animatedHeight = useRef(new Animated.Value(0)).current;

  // 初始化动画高度为折叠状态高度
  useEffect(() => {
    animatedHeight.setValue(collapsedHeight);
  }, [collapsedHeight]);

  const toggleExpand = () => {
    Animated.timing(animatedHeight, {
      toValue: isExpanded ? collapsedHeight : fullTextHeight,
      duration: 300,
      useNativeDriver: false, // 高度动画不支持原生驱动
    }).start();
    setIsExpanded(!isExpanded);
  };

  return (
    <View style={styles.container}>
      {/* 测量全量文本高度(隐藏) */}
      <Text
        style={[styles.commentText, styles.hiddenText]}
        onLayout={(e) => setFullTextHeight(e.nativeEvent.layout.height)}
      >
        {reviewComment}
      </Text>
      {/* 测量3行文本高度(隐藏) */}
      <Text
        style={[styles.commentText, styles.hiddenText]}
        numberOfLines={3}
        onLayout={(e) => setCollapsedHeight(e.nativeEvent.layout.height)}
      >
        {reviewComment}
      </Text>
      {/* 实际显示的文本容器,通过动画控制高度 */}
      <Animated.View style={{ height: animatedHeight, overflow: 'hidden' }}>
        <Text style={styles.commentText}>{reviewComment}</Text>
      </Animated.View>
      {/* 仅当文本超出3行时显示按钮 */}
      {fullTextHeight > collapsedHeight && (
        <TouchableOpacity onPress={toggleExpand} style={styles.toggleButton}>
          <Text style={styles.toggleText}>
            {isExpanded ? '收起' : 'Read More'}
          </Text>
        </TouchableOpacity>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    padding: 16,
  },
  commentText: {
    fontSize: 14,
    lineHeight: 20,
    color: '#333',
  },
  hiddenText: {
    position: 'absolute',
    opacity: 0,
    left: 0,
    right: 0,
  },
  toggleButton: {
    marginTop: 8,
  },
  toggleText: {
    color: '#007AFF',
    fontSize: 14,
  },
});

export default ReviewComment;

关键细节说明

  • 隐藏文本测量:两个隐藏文本和实际显示文本使用完全一致的样式(字体、行高、宽度),确保测量的高度和真实显示高度匹配。
  • 动画兼容性:useNativeDriver设为false,因为高度属于布局属性,React Native原生驱动不支持这类动画。
  • 边界处理:判断fullTextHeight > collapsedHeight,只有当文本确实超出3行时才显示展开按钮,避免无效交互。

内容的提问来源于stack exchange,提问作者MagomedRasul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:02:44