我正在尝试访问我应用程序中 React [Native] 组件的 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 有问题。 为什么?
最佳答案
在这种情况下,您需要将子项声明或转换为 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>;
}
通过这种方式,您可以在没有任何警告的情况下访问属性 prop。
快乐的代码。 :-)
关于reactjs - 如何使用 TypeScript 以类型安全的方式访问 React 子元素 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58818153/