[英]Typescript React Functional Component with props.children
I'm trying to make a component that will show a loading circle when the prop isLoading is true, and otherwise show the child component.我正在尝试制作一个组件,当道具 isLoading 为 true 时将显示加载圆圈,否则显示子组件。 I'd like to use the component in other components likes this...
我想在像这样的其他组件中使用该组件...
import Loading from './Loading.tsx'
...
const [isLoading,setLoading] = React.useState(false);
return (
<Loading isLoading={isLoading}>
<div>this component will show when loading turns to true</div>
</Loading> );
I'm getting the typscript error我收到打字稿错误
Type '({ isLoading, color, children, }: PropsWithChildren<LoadingProps>) => Element | { children: ReactNode; }' is not assignable to type 'FunctionComponent<LoadingProps>'.
Type 'Element | { children: ReactNode; }' is not assignable to type 'ReactElement<any, any> | null'.
Type '{ children: ReactNode; }' is missing the following properties from type 'ReactElement<any, any>': type, props, key TS2322
Can someone point out what I'm doing wrong?有人可以指出我做错了什么吗?
import React, { FunctionComponent } from 'react';
import { CircularProgress } from '@material-ui/core';
type LoadingProps = {
isLoading: boolean;
color: 'primary' | 'secondary' | 'inherit' | undefined;
};
const Loading: FunctionComponent<LoadingProps> = (props) => {
if(props.isLoading){
return <CircularProgress color={props.color || 'primary'} />
}
return props.children;
};
export default Loading;
That´s because of return props.children
.那是因为
return props.children
。
You should wrapper it with a fragment, like this:你应该用一个片段包装它,像这样:
const Loading: React.FC<LoadingProps> = (props) => {
return props.isLoading ? (
<CircularProgress color={props.color || "primary"} />
) : (
<>{props.children}</>
);
};
It is recommended (see here ) to explicitly define the type of your children when using React.FunctionComponents as your function type.当使用 React.FunctionComponents 作为你的函数类型时,建议(见这里)明确定义你的孩子的类型。
So所以
type LoadingProps = {
isLoading: boolean
color: 'primary' | 'secondary' | 'inherit' | undefined
children: React.ReactNode
}
This will also ensure correct typing on the return.这也将确保在返回时正确键入。
The link of @sam256 is right but it says that there is a new syntax via React.FunctionComponent where children are implicit. @sam256 的链接是正确的,但它表示通过 React.FunctionComponent 有一种新语法,其中子项是隐式的。
New syntax:新语法:
const Title: React.FunctionComponent<{ title: string }> = ({
children,
title,
}) => <div title={title}>{children}</div>;
Should work like this:应该像这样工作:
<Title title="my string">
<div>Implicit child</div>
</Title>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.