JSX 元素类型“字符串”不是 JSX 元素的构造函数。typescript

IT技术 javascript reactjs typescript react-native
2021-05-11 04:48:42

所以我一直在研究一个可重用的图标元素,我可以在任何类中调用它,只传递一个<Icon name="chat" />包含图标特定颜色的字符串..这个错误是我提出的上一个问题的结果..你可以找到链接以下

在此之前我提过一个问题:

icon.ts 文件

const iconsList = {
    heart: '&#xe800;',
    star: '&#xe801;',
    like: '&#xe800;',
    dislike: '&#xe802;',
    flash: '&#xe803;',
    marker: '&#xf031;',
    filter: '&#xf0b0;',
    user: '&#xf061;',
    circle: '&#xf039;',
    hashtag: '&#xf029;',
    calendar: '&#xf4c5;',
    chevronLeft: '&#xf004;',
    optionsV: '&#xf142;',
    optionsH: '&#xf141;',
    chat: '&#xf4ac;',
    explore: '&#xf50d;'
};

interface Props{
    name: keyof typeof iconsList;
}

const Icon = ({name }: Props) => {
    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return icon;
 };

export default Icon;

配置文件.tsx

import React from 'react';
import styles from '../assets/styles';

import {
  ScrollView,
  View,
  Text,
  ImageBackground,
  TouchableOpacity
} from 'react-native';
import Icon from '../components/Icon';
const Profile = () => {
return (

<TouchableOpacity>
  <Text style={styles.topIconLeft}>
    <Icon name="chevronLeft" />
  </Text>
</TouchableOpacity>

);
}

这一行<Icon name="chevronLeft" />抱怨错误“JSX 元素类型‘字符串’不是 JSX 元素的构造函数。ts(2605)

截屏 : 在此处输入图片说明

1个回答

string不是react组件的有效返回值。react组件总是必须返回一个ReactDOM元素或一个Fragment实现该render方法元素你可以试试

const Icon : React.SFC<Props> = ({name }: Props) => {
    let icon = iconsList[name];
    icon = icon.substr(3);
    icon = String.fromCharCode(parseInt(icon, 16));

    return <>{icon}</>;
 };

实际上,如果您重命名icon.tsicon.tsx. 根据您的编译器设置,该<>{icon}</>部分可能无法正确识别为 JSX 标记。