简体   繁体   English

使用 Typescript 将 prop 渲染为字符串或组件

[英]Render prop as string or component with Typescript

I have a function that conditionally renders/returns a string or a dynamic component depending on what type the prop is:我有一个 function 有条件地呈现/返回字符串或动态组件,具体取决于道具的类型:

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

However, with the above code I get the following message from Typescript:但是,使用上面的代码,我从 Typescript 收到以下消息:

JSX element type 'Component' does not have any construct or call signatures.ts(2604) JSX 元素类型“组件”没有任何构造或调用 signatures.ts(2604)

I have read other answers on this topic on SO, but still haven't concluded an answer.我已经在 SO 上阅读了有关主题其他答案,但仍未得出答案。

<Component /> is JSX notation and it's basically telling React to render this component. <Component />是 JSX 表示法,它基本上告诉 React 渲染这个组件。 That's only possible in React Component which has to return JSX code.这只有在必须返回 JSX 代码的React Component中才有可能。 To solve the problem you could just check if argument is valid element and then render it conditionally in desired 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>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM