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

React Native:点击按钮无法打开react-native-image-modal的问题求助

你需要通过ref调用react-native-image-modal的内置open()方法,实现点击按钮打开模态框的功能。以下是修改后的完整代码:

import { useRef } from 'react';
import { TouchableOpacity, Text, View } from 'react-native';
import ImageModal from 'react-native-image-modal';

const YourComponent = () => {
  // 创建ImageModal的ref,用于控制模态框显示
  const imageModalRef = useRef(null);

  return (
    <>
      <TouchableOpacity
        activeOpacity={0.6}
        onPress={() => {
          // 调用ref的open方法打开模态框
          imageModalRef.current?.open();
        }}
        style={{
          borderWidth: 1,
          borderColor: '#FF9898',
          borderRadius: 50,
          position: 'absolute',
        }}>
        <Text style={{ color: '#ffc107', fontWeight: '500', fontSize: 11, paddingVertical: 3, paddingHorizontal: 2 }}>
          See Image
        </Text>
      </TouchableOpacity>
      <View>
        <ImageModal
          ref={imageModalRef} // 将ref绑定到ImageModal组件
          resizeMode="contain"
          imageBackgroundColor="#000000"
          style={{
            width: 400,
            height: 400,
          }}
          source={{
            uri: 'https://res.cloudinary.com/duldhdjsj/image/upload/v17042/litnldacr4.jpg',
          }}
        />
      </View>
    </>
  );
};

export default YourComponent;

关键改动说明:

  • 新增useRef钩子创建imageModalRef,用于获取ImageModal组件实例
  • 在TouchableOpacity的onPress回调中,调用imageModalRef.current?.open()触发模态框打开(可选链操作符避免null报错)
  • 移除原代码中无效的modalRef属性,将ref直接绑定到ImageModal组件
  • 修正Text组件的className(React Native不支持className,改用style属性)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:22:06