[英]Typescript and React: Type 'Element' is not assignable to type 'FunctionComponent<{}>'
[英]Typescript type definition for FunctionComponent and children
我正在尝试了解打字稿,我对它很陌生,并且在语法后面有点丢失。 我正在尝试定义一个 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}) => {...}
但两者似乎都不起作用。
你可以定义你的组件,给它 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 正在为你做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.