我有反应项目,Create-React-App
有以下包(提到与我的问题相关的包(:
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1",
"typescript": "^3.9.2",
"@typescript-eslint/eslint-plugin": "^2.33.0",
"@typescript-eslint/parser": "^2.33.0"
我已经创建了一个简单的 HOC(到目前为止它什么都不做,但我稍后会添加我的逻辑(,如下所示:
type Props = {
[key: string]: any;
};
const connect = function (Component: FunctionComponent): FunctionComponent {
const ComponentWrapper = function (props: Props): ReactElement {
return <Component {...props} />;
};
return ComponentWrapper;
};
并像这样导出我的组件:
const Test: FunctionComponent<Props> = function ({ message }: Props) {
return (
<div>{message}</div>
);
};
export default connect(Test);
并像这样使用此组件:
<Test message="Testing message" />
但是在编译器中出现错误:
Type '{ message: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
Property 'message' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'. TS2322
我已经尝试了人们在Google上找到的其他类似的Stack Overflow问题和文章中的建议,但到目前为止没有任何效果。
// This is the piece we were missing --------------------v
const connect = function (Component: React.FC): React.FC<Props> {
const ComponentWrapper = function (props: Props): JSX.Element {
return <Component {...props} />;
};
return ComponentWrapper;
};
重新启动编译器后,它将正常工作。
connect
函数的返回值的类型是需要Props
的功能组件,而不是裸功能组件。
另请参阅备忘单
这不是父组件的问题。这是子组件的问题。只需在子组件中定义 props,父组件中的此错误就会消失。
父级: <子组件 />
但也要在子组件中定义,如下所示:
子:导出默认函数加载(道具( {