我试图在我的应用程序中访问React原生组件的props (它保证是我的自定义类型ItemTemplate元素的实例)
const children = React.Children.toArray(this.props.children);
return children.find(t => t.props.itemKey == key);但是,在第二行中,当我尝试访问t.props时,我得到的是:
Property 'props' does not exist on type 'ReactElement<ItemTemplate, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | ... 13 more ... | (ReactElement<...>[] & ReactPortal)'.
Property 'props' does not exist on type 'ReactElement<ItemTemplate, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>[] & string'.代码确实正常工作,但是TypeScript (3.6.3) IntelliSense在抱怨。为什么?
发布于 2021-05-20 21:19:02
在这种情况下,您需要声明或将子节点转换为ReactElement。这里有一个将组件从nextjs链接到自定义NavLink的示例:
import { ReactElement, cloneElement } from 'react';
import Link, { LinkProps } from 'next/link';
type NavigationData = {
currentPath: string;
pathsToMatch: string[] | string;
activeClassName: string;
children: ReactElement;
};
type NavLinkProps = LinkProps & NavigationData;
export default function NavLink({
currentPath,
pathsToMatch,
activeClassName,
children,
...props
}: NavLinkProps): ReactElement {
function GetActiveLink(
currentPath: string,
paths: string | string[],
activeClassName: string
): string {
if (currentPath === '/' && paths === '/') {
return activeClassName;
} else if (currentPath !== '/' && paths.indexOf(currentPath) !== -1)
{
return activeClassName;
}
return '';
}
let className: string = children.props.className || '';
className += ` ${GetActiveLink(currentPath, pathsToMatch, activeClassName)}`;
return <Link {...props}>{cloneElement(children, { className })}</Link>;
}通过这种方式,您可以在没有任何警告的情况下访问属性支柱。
快乐的密码。:-)
发布于 2019-11-12 12:27:59
使用方式如下:
const children: Array<ReactChild> = React.Children.toArray(this.props.children);
return children.find(t => t.props.itemKey == key);或者使用自定义类型ItemTemplate:
const children: Array<ItemTemplate> = React.Children.toArray(this.props.children);
return children.find(t => t.props.itemKey == key);https://stackoverflow.com/questions/58818153
复制相似问题