JSX 元素类型 'string' 不是 JSX 元素的构造函数.打字稿 [英] JSX element type 'string' is not a constructor function for JSX elements. Typescript
问题描述
所以我一直在研究一个可重用的图标元素,我可以在任何类中调用它,只需传递一个包含特定颜色的字符串 <Icon name="chat"/>
图标.. 这个错误是我上一个问题的结果..你可以找到下面的链接
string
不是 React 组件的有效返回值.React 组件总是必须返回一个 ReactDOM
元素或一个 Fragment
,它实现了 render
方法.你可以试试
const 图标:React.SFC=({名称}:道具)=>{让 icon = iconsList[name];icon = icon.substr(3);icon = String.fromCharCode(parseInt(icon, 16));返回 <>{icon}</>;};
实际上,如果您将icon.ts
重命名为icon.tsx
,也不会受到伤害.根据您的编译器设置,<>{icon}</>
部分可能无法正确识别为 JSX 标记.
So i have been working on a reusable icon element that I can call in any class and just pass a string <Icon name="chat" />
that contain the specific colour of the icon .. This error is the result of the previous question I raised .. you can find the link below
I raised a question early before this:
icon.ts file
const iconsList = {
heart: '',
star: '',
like: '',
dislike: '',
flash: '',
marker: '',
filter: '',
user: '',
circle: '',
hashtag: '',
calendar: '',
chevronLeft: '',
optionsV: '',
optionsH: '',
chat: '',
explore: ''
};
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;
profile.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>
);
}
This line of <Icon name="chevronLeft" />
complains with an error of "JSX element type 'string' is not a constructor function for JSX elements.ts(2605)
Screenshot :
string
is not a valid return value for a react component. A react component always has to return a ReactDOM
element or a Fragment
, that implements the render
method. You can try
const Icon : React.SFC<Props> = ({name }: Props) => {
let icon = iconsList[name];
icon = icon.substr(3);
icon = String.fromCharCode(parseInt(icon, 16));
return <>{icon}</>;
};
And actually it won't hurt if you renamed icon.ts
to icon.tsx
. Depending on your compiler settings the <>{icon}</>
part might not get recognized correctly as JSX markup.
这篇关于JSX 元素类型 'string' 不是 JSX 元素的构造函数.打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!