[英]TS2345: Argument of type 'ReactNode' is not assignable to parameter of type 'ReactElement'
TS2345: Argument of type 'ReactNode' is not assignable to parameter of type 'ReactElement<any, string |
TS2345:“ReactNode”类型的参数不可分配给“ReactElement<any, string | 类型的参数” ((props: any) => ReactElement<any, any> | null) |
((props: any) => ReactElement<any, any> | null) | (new (props: any) => Component<any, any, any>)> |
(new (props: any) => 组件<any, any, any>)> | ReactElement<any, string |... 1 more... |
ReactElement<any, string |... 1 更多... | (new (props: any) => Component<...>)>[]'.
(new (props: any) => 组件<...>)>[]'。 Type 'undefined' is not assignable to type 'ReactElement<any, string |
类型 'undefined' 不可分配给类型 'ReactElement<any, string | ((props: any) => ReactElement<any, any> | null) |
((props: any) => ReactElement<any, any> | null) | (new (props: any) => Component<any, any, any>)> |
(new (props: any) => 组件<any, any, any>)> | ReactElement<any, string |... 1 more... |
ReactElement<any, string |... 1 更多... | (new (props: any) => Component<...>)>[]'.
(new (props: any) => 组件<...>)>[]'。
Here's my code:这是我的代码:
import React, {forwardRef, ReactNode} from 'react';
import {mergeClasses} from '../../utils';
import {ArrowLeft} from '../../icons';
import {BreadcrumbsProps} from './declarations/Breadcrumbs.types';
import defaultClasses from './styles/Breadcrumbs.module.css'
export const Breadcrumbs = forwardRef<HTMLLabelElement, BreadcrumbsProps>(
({
separator="/",
children,
back,
classNames,
onClick,
}) => {
const styles = mergeClasses(defaultClasses, classNames);
const Back = (
<button className={styles.back} type='button' onClick={onClick}>
<ArrowLeft/>
<span>Back</span>
</button>
)
const Separator = <span className={styles.separator}>{separator}</span>;
const getValidChild = (itemToRender: ReactNode, delta: number, index: number) => {
const SeparatorWithKey = React.cloneElement(Separator, { key: `${index}_separator` });
return index === 0 ? [itemToRender] : [SeparatorWithKey, itemToRender];
};
const getItemsByChildren = () => {
const delta = React.Children.toArray(children).length;
return (
React.Children.map(children, (child: React.ReactElement, index) => {
return (
child &&
getValidChild(
React.cloneElement(child),
delta,
index
)
);
}));
};
return (
<div className={styles.wrapper}>
{back && Back}
<ul className={styles.breadcrumbs}>
{getItemsByChildren()}
</ul>
</div>
);
},
);
You've declared the type of child
wrong here:您在这里声明了
child
的类型错误:
React.Children.map(children, (child: React.ReactElement, index) => {
children
is of type React.ReactNode
. children
是React.ReactNode
类型。 React.Element
is something entirely different. React.Element
是完全不同的东西。
You don't need to type this argument at all, React.Children.map
already can infer the correct type here.你根本不需要输入这个参数,
React.Children.map
已经可以在这里推断出正确的类型。 Just this works just fine:只是这工作得很好:
React.Children.map(children, (child, index) => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.