reactjs - 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}) => {...}
但两者似乎都不起作用。
解决方案
你可以定义你的组件,给它 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 正在为您执行此操作。
推荐阅读
- c# - 如何从 C# 运行 nodejs 包
- sql-server - 在事务 SQL 中删除某个列之后的其余列
- react-native - React-native + apollo:网络请求失败
- php - PHP 如何在 Firebase 的表中添加/插入表
- python - Jupyter notebook 找不到模块
- python - 使用 conda 安装 CUDA 驱动程序后的 libcuda.so.1
- angular - Ionic 3 - firebase 插件 - 无法获取手机的令牌
- c++ - VSC 将默认编译器设置为 clang++ -std=c++17 或 g++ -std=c++17
- maven - ClassNotFoundException org.hornetq.jms.client.HornetQTopic
- amazon-web-services - AWS EC2 实例在重启后失去 GPU 支持