![](/img/trans.png)
[英]How to access props.children in a stateless functional component in react?
[英]Typescript React Functional Component with props.children
我正在嘗試制作一個組件,當道具 isLoading 為 true 時將顯示加載圓圈,否則顯示子組件。 我想在像這樣的其他組件中使用該組件...
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> );
我收到打字稿錯誤
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
有人可以指出我做錯了什么嗎?
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;
那是因為return props.children
。
你應該用一個片段包裝它,像這樣:
const Loading: React.FC<LoadingProps> = (props) => {
return props.isLoading ? (
<CircularProgress color={props.color || "primary"} />
) : (
<>{props.children}</>
);
};
當使用 React.FunctionComponents 作為你的函數類型時,建議(見這里)明確定義你的孩子的類型。
所以
type LoadingProps = {
isLoading: boolean
color: 'primary' | 'secondary' | 'inherit' | undefined
children: React.ReactNode
}
這也將確保在返回時正確鍵入。
@sam256 的鏈接是正確的,但它表示通過 React.FunctionComponent 有一種新語法,其中子項是隱式的。
新語法:
const Title: React.FunctionComponent<{ title: string }> = ({
children,
title,
}) => <div title={title}>{children}</div>;
應該像這樣工作:
<Title title="my string">
<div>Implicit child</div>
</Title>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.