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

React Native地图标记渲染SVG图标报错:不存在于JSX.IntrinsicElements类型

解决JSX.IntrinsicElements图标不存在错误

错误原因

你当前的问题核心是:数据源里的type字段存的是字符串(比如'ShellIcon'),而非实际导入的React组件引用。当你把这个字符串赋值给MarkerIcon并当作组件使用时,JSX会默认将其识别为HTML原生标签(比如<div>这类),但ShellIcon并不是原生HTML元素,因此TypeScript会抛出“不存在于类型'JSX.IntrinsicElements'”的错误。

修复步骤

1. 修改数据源,使用组件引用而非字符串

将staticData里的type值从字符串替换为你导入的实际组件:

import ShellIcon from '../../../assets/images/xxx.svg';
import BPIcon from '../../../assets/images/xxx.svg';
import TexacoIcon from '../../../assets/images/xx.svg';

const staticData = [
  {
    name: 'test station',
    type: ShellIcon, // 直接传入组件引用,而非字符串
    price: '15.00p',
    coordinates: {
      latitude: 52.56504897473243,
      longitude: -1.9835459043698045,
    },
  },
  {
    name: 'test station',
    type: BPIcon,
    price: '10.00p',
    coordinates: {
      latitude: 52.564655445785036,
      longitude: -1.9895132194946084,
    },
  },
  {
    name: 'test station',
    type: TexacoIcon,
    price: '12.00p',
    coordinates: {
      latitude: 52.56675992926686,
      longitude: -1.9925531724706291,
    },
  },
];

2. 修正遍历中的变量错误

你原代码的map循环存在变量名不匹配问题:参数是marker却使用了item,key用了index但循环变量是i,需同步修正:

<MapView ..>
  {staticData.map((marker, index) => {
    const MarkerIcon = marker.type;

    return (
      <Marker key={index} coordinate={marker.coordinates} ref={markerRef}>
        <MapPin price={marker.price} icon={MarkerIcon} />
      </Marker>
    );
  })}
</MapView>

3. 正确定义MapPin组件的Props类型

确保MapPin的Props中icon的类型为React组件类型,避免TypeScript类型报错:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

// 定义Props类型
type MapPinProps = {
  price: string;
  icon: React.ElementType; // 明确这是React组件类型
};

const MapPin = ({ price, icon: Icon }: MapPinProps) => (
  <View style={styles.bubbleContainer}>
    <View style={styles.bubbleContent}>
      <Icon /> {/* JSX要求自定义组件首字母大写,因此将icon重命名为Icon */}
      <Text style={styles.bubblePrice}>{price}</Text>
    </View>
    <View style={styles.bubbleArrow} />
  </View>
);

// 样式示例(根据你的实际需求调整)
const styles = StyleSheet.create({
  bubbleContainer: {
    alignItems: 'center',
  },
  bubbleContent: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 8,
    backgroundColor: '#fff',
    borderRadius: 8,
  },
  bubblePrice: {
    marginLeft: 4,
    fontWeight: 'bold',
  },
  bubbleArrow: {
    width: 0,
    height: 0,
    borderLeftWidth: 6,
    borderRightWidth: 6,
    borderTopWidth: 8,
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent',
    borderTopColor: '#fff',
  },
});

export default MapPin;

关键说明

  • JSX规范要求自定义组件名称必须首字母大写,因此在MapPin组件中我们将icon重命名为Icon后再使用。
  • 直接传递组件引用而非字符串,能让React正确识别这是自定义组件,而非原生HTML元素,从而彻底解决TypeScript的类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:05:12