【问题标题】:Property does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'类型'IntrinsicAttributes & { children?: ReactNode; 上不存在属性}'
【发布时间】:2020-09-03 07:00:32
【问题描述】:

我有 Create-React-App 创建的 react 项目有以下包(提到与我的问题相关的包):

"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 问题和文章中提出的建议,但到目前为止还没有任何效果。

【问题讨论】:

  • 如果您认为您已经研究过的这个问题可能存在重复,请务必列出它们,并说明为什么它们不适用。但是,通常最好不要声明根本没有重复项,因为您无法检查所有可能的问题。读者希望您愿意接受一份副本(如果提供)。
  • @halfer 早些时候我得到了很多反对票,只是因为 SO 上的一些用户发现了重复项,尽管这些不是重复项,我不得不删除这些问题。感谢您的关心。

标签: reactjs typescript create-react-app react-hoc intrinsicattributes


【解决方案1】:
// 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的函数组件,而不是裸函数组件。

另请参阅cheatsheet

【讨论】:

  • 如果解释一下它的工作原理,这将大大改进。
猜你喜欢
  • 2021-07-12
  • 2021-08-20
  • 1970-01-01
  • 2018-10-14
  • 1970-01-01
  • 2022-08-18
  • 2021-09-06
  • 2020-11-07
  • 2020-01-24
相关资源
最近更新 更多