reactjs - 如何使用 TypeScript 以类型安全的方式访问 React 子元素 Prop ?

标签 reactjs typescript react-native react-props typescript-types

我正在尝试访问我应用程序中 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/

相关文章:

javascript - 我们为什么以及在哪里需要 bundle.js?

reactjs - 从外部material-ui组件访问主题

javascript - 如何过滤可能是几个树级别深度的父子数组的多个属性

reactjs - 如何在加载时打开 React Native Maps 标记的标注

javascript - undefined 不是一个函数(评估'_this.props.navigation.navigate')

javascript - 循环状态并检查对象是否存在

reactjs - 从构建 React.js 中排除 .js 文件

node.js - 如何在 Dockerfile 中编译 typescript

javascript - 具有依赖性的 React useState Hook

react-native - Mapbox React Native,ShapeSource#images 已弃用,请使用 Images#images