首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用TypeScript以类型安全的方式访问子元素道具?

如何使用TypeScript以类型安全的方式访问子元素道具?
EN

Stack Overflow用户
提问于 2019-11-12 11:53:43
回答 2查看 1.4K关注 0票数 3

我试图在我的应用程序中访问React原生组件的props (它保证是我的自定义类型ItemTemplate元素的实例)

代码语言:javascript
复制
const children = React.Children.toArray(this.props.children);
return children.find(t => t.props.itemKey == key);

但是,在第二行中,当我尝试访问t.props时,我得到的是:

代码语言:javascript
复制
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在抱怨。为什么?

EN

回答 2

Stack Overflow用户

发布于 2021-05-20 21:19:02

在这种情况下,您需要声明或将子节点转换为ReactElement。这里有一个将组件从nextjs链接到自定义NavLink的示例:

代码语言:javascript
复制
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>;
}

通过这种方式,您可以在没有任何警告的情况下访问属性支柱。

快乐的密码。:-)

票数 2
EN

Stack Overflow用户

发布于 2019-11-12 12:27:59

使用方式如下:

代码语言:javascript
复制
const children: Array<ReactChild> = React.Children.toArray(this.props.children);
return children.find(t => t.props.itemKey == key);

或者使用自定义类型ItemTemplate:

代码语言:javascript
复制
const children: Array<ItemTemplate> = React.Children.toArray(this.props.children);
return children.find(t => t.props.itemKey == key);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58818153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档