【问题标题】:Correct type to set for a renderAs Propery in Typescript React Components?在 Typescript React 组件中为 renderAs 属性设置正确的类型?
【发布时间】:2023-03-26 11:16:02
【问题描述】:

组件有时需要能够呈现为不同的 HTML 元素,具体取决于其上下文。例如,这个Card 组件。

import React from 'react';

export type Props = {
    className?: string,
    renderAs: any
}

export const Card: React.FC<Props> = function Card({ renderAs, className, children }) {
    const Element = renderAs;
    return (
        <Element className={`card  ${ className ? className:'' }`}>
            { children }
        </Element>
    )
}

在实际使用组件时,一切正常:

<Card renderAs="section">...</Card>
<Card renderAs="div">...</Card>

但我不确定,对于这个用例,如果使用 renderAs: any 是正确的类型,我希望能对此有所了解!

提前谢谢你!

【问题讨论】:

  • 这能回答你的问题吗? (stackoverflow.com/questions/54049871/…)
  • 我认为可以,但恐怕我没有足够的经验将其应用于我的情况。如果我没看错,我必须自己添加一个新类型?

标签: javascript reactjs typescript


【解决方案1】:

你传递的实际类型是React.ElementType,离开

export type Props = {
    className?: string,
    renderAs: React.ElementType
}

你的意思是你想让renderAs被设置为一些内在的JSX元素,比如sectiondivspan ...

【讨论】:

  • 不幸的是,这不适用于我的使用方式。也许当你这样定义它时,你必须以不同于我描述的方式使用它?
  • 我在这里做了一个简单的实现:codesandbox.io/s/react-typescript-mfrh2。请注意,我理所当然地认为CartCard 是一个错字,实际上应该是Card。那是我的错误吗?
  • 谢谢!一切正常,我之前只是遇到错误,但现在一切正常,谢谢:)
猜你喜欢
  • 2020-03-19
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 2022-07-09
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 2015-12-02
相关资源
最近更新 更多