【问题标题】:Render prop as string or component with Typescript使用 Typescript 将 prop 渲染为字符串或组件
【发布时间】:2020-03-14 22:04:28
【问题描述】:

我有一个函数可以根据 prop 的类型有条件地呈现/返回字符串或动态组件:

const renderValue = (value: string | React.ReactNode) => {
  if (React.isValidElement(value)) {
    const Component = value
    return <Component />
  }
  return value
}

但是,使用上面的代码,我从 Typescript 收到以下消息:

JSX 元素类型“组件”没有任何构造或调用 signatures.ts(2604)

我已经阅读了otheranswersonthistopic关于SO,但仍未得出答案。

【问题讨论】:

  • 如果从 type 中删除 'string' 会发生什么?
  • 你可以使用return &lt;value /&gt;
  • @kinduser 什么都没有发生。
  • @RaminRezazadeh 组件必须大写。
  • 你有的看起来像一个功能组件,你的功能可以用作功能组件吗? const RenderValue?

标签: javascript reactjs typescript


【解决方案1】:

&lt;Component /&gt; 是 JSX 表示法,它基本上告诉 React 渲染这个组件。这只有在必须返回 JSX 代码的 React Component 中才有可能。要解决该问题,您只需检查参数是否为有效元素,然后在所需的React Component

中有条件地呈现它
import React from 'react'

interface Props {
   value: string | React.ReactNode
}

const SomeComponent:React.FC<Props> = ({value}) => {
  return (
    <div>
      <span>Hello World</span>
      {React.isValidElement(value) ? <Component/> : value}
    </div>
  )
}

【讨论】:

  • 谢谢。刚刚编辑了答案,如果值不是有效元素,则只渲染字符串
猜你喜欢
  • 1970-01-01
  • 2020-12-20
  • 2021-09-19
  • 1970-01-01
  • 2023-02-03
  • 2019-05-11
  • 2015-05-05
  • 2020-12-27
  • 2021-08-03
相关资源
最近更新 更多