我正在将TypeScript与React一起使用,当我运行tsc / jest测试时,它返回与以下类似的所有组件的错误:
Property 'prop name' does not exist on type '{ children?: ReactNode; }'.
文件夹/组件结构:
– ExampleComponent
- component.tsx
- index.ts
- styles.css
- styles.css.d.ts
Component.tsx
import React from 'react';
import { Text } from 'designlibrary';
import styles from './styles.css';
export interface TypeExports {
title: string;
text: string;
}
export const Blurb: React.FunctionComponent = (props: TypeExports) => (
<div className={styles.blurb}>
<Text color='primary' size='h3' type='h3'>
{props.title}
</Text>
<Text color='primary' size='p1' type='p'>
{props.text}
</Text>
</div>
);
index.ts
export { Blurb } from './component';
styles.css.d.ts
interface CssExports {
blurb: string;
}
declare var cssExports: CssExports;
export = cssExports;
在导出类时遇到类似的错误,并且由于我将以上内容添加到.style.css.d.ts
文件中,因此它解决了所有与CSS相关的打字稿错误。
上面的组件仍然返回的错误示例是:
Property 'text' does not exist on type '{ children?: ReactNode; }'.
编辑:
在尼古拉斯帮助下,这是工作组件的结构:
export interface TypeExports {
title: string;
text: string;
}
export const Blurb: React.FunctionComponent<TypeExports> = (props) =>
<div className={styles.blurb}>
<Text color='primary' size='h3' type='h3'>
{props.title}
</Text>
<Text color='primary' size='p1' type='p'>
{props.text}
</Text>
</div>
答案 0 :(得分:1)
React.FunctionComponent是generic。您可以告诉它您的道具是什么,它将相应地调整其类型。由于您没有告诉您道具是什么,因此它认为没有道具。改为这样做:
// I'd probably name this interface "BlurbProps", but that's up to you
export interface TypeExports {
title: string;
text: string;
}
export const Blurb: React.FunctionComponent<TypeExports> = (props) => {
// etc
}
我在(props)
上省略了类型,因为现在可以推断出它。如果愿意,欢迎您再次重申类型并将其保留为(props: TypeExports)
,但重要的是在<TypeExports>
之后添加React.FunctionComponent