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

React Native聊天应用:点击视频消息弹窗播放视频问题求助

问题分析与解决

你的代码核心问题是把Modal组件放在了TouchableOpacity的onPress回调里返回——React的事件处理函数不会处理返回的JSX,所以点击后Modal根本不会被渲染出来,自然没有任何反应。

修复步骤:

  1. 将Modal组件从onPress回调中移出,放到组件的主渲染树中,通过modalVisible状态控制显示/隐藏。
  2. 给Video组件添加必要的属性,确保能正常播放(比如useNativeControls、shouldPlay)。
  3. 简化onPress逻辑,只负责切换modalVisible状态。

修改后的完整代码片段:

import { Video } from "expo-av";
import { Modal, TouchableOpacity, ImageBackground, View } from "react-native";
import AntDesign from "@expo/vector-icons/AntDesign";

// ... 其他代码 ...

const [modalVisible, setModalVisible] = React.useState(false);
const [currentVideoUrl, setCurrentVideoUrl] = React.useState("");

// ... 其他代码 ...

{videoThumbnailUrl && (
  <TouchableOpacity
    onPress={() => {
      setCurrentVideoUrl("http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4");
      setModalVisible(true);
    }}
  >
    <ImageBackground
      source={{ uri: videoThumbnailUrl }}
      resizeMode="cover"
      style={styles.image}
    >
      <AntDesign name="playcircleo" color="white" size={80} />
    </ImageBackground>
  </TouchableOpacity>
)}

// 将Modal放在主渲染树中
<Modal
  visible={modalVisible}
  onRequestClose={() => setModalVisible(false)}
  animationType="slide" // 可选:添加过渡动画
>
  <View style={{ flex: 1, backgroundColor: "black", justifyContent: "center", alignItems: "center" }}>
    {/* 添加关闭按钮 */}
    <TouchableOpacity 
      style={{ position: "absolute", top: 40, right: 20, zIndex: 1 }}
      onPress={() => setModalVisible(false)}
    >
      <AntDesign name="close" color="white" size={30} />
    </TouchableOpacity>
    <Video
      source={{ uri: currentVideoUrl }}
      style={{ height: "80%", width: "100%" }}
      useNativeControls={true} // 显示原生播放控件
      shouldPlay={modalVisible} // 打开Modal时自动播放
      resizeMode="contain" // 保持视频比例
    />
  </View>
</Modal>

关键修改说明:

  • Modal的位置:必须放在组件的渲染输出中,不能在事件回调里动态返回,React只会处理渲染阶段返回的JSX。
  • Video属性补充:useNativeControls让用户能控制播放/暂停,shouldPlay确保打开Modal时自动开始播放,resizeMode优化视频显示效果。
  • 状态管理:新增currentVideoUrl状态,方便后续切换不同视频消息时复用Modal。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:18:17