首页 > 解决方案 > FunctionComponent 和子项的 Typescript 类型定义

问题描述

我试图让我的头脑围绕打字稿,我对它相当陌生,并且在语法后面有点失去它。我正在尝试定义一个 HOC 来在我的测试中进行包装。

import React, {FunctionComponent, ReactNode} from 'react';
import {ThemeProvider} from "styled-components";
import theme from "../components/Global/theme/theme.style";

const mountWithTheme: FunctionComponent = ({children}: { children?: ReactNode }) => (
    <ThemeProvider theme={theme}>{children}</ThemeProvider>
);

export default mountWithTheme;

现在,我知道 React 中有一个类型

type PropsWithChildren<P> = P & { children?: ReactNode };

如何在我的定义中使用它来避免重新发明轮子?类型定义对我来说不是很清楚,我试过了

{children}: PropsWithChildren

const mountWithTheme: FunctionComponent<PropsWithChildren> = ({children}) => {...}

但两者似乎都不起作用。

标签: reactjstypescriptreact-typescript

解决方案


你可以定义你的组件,给它 props 类型作为参数:

import React, {FunctionComponent} from 'react';

type MyProps = {
  color: "red"
}

const mountWithTheme: FunctionComponent<MyProps> = (props) => (
  <div color={props.color}>{props.children}</div>
);

props将是类型PropsWithChildren<MyProps>,但 FunctionComponent 正在为您执行此操作。


推荐阅读