【问题标题】:How to create a react component map with correct type [duplicate]如何创建具有正确类型的反应组件映射[重复]
【发布时间】:2021-12-11 22:01:07
【问题描述】:

我正在尝试使用 typescript 创建一个反应组件映射,它根据键返回相应的组件,Item1 和 Item2 都是反应组件。

const componentMap: {[key: string]: JSX. Element} = {
 "Item1": Item1,
 "Item2": Item2,
}

下面是item1和item2的定义

type itemProps = {
  props1: string,
  props2: boolean,
}

export const Item1 = (): JSX.Element => {
  return (<div/>)
}

export const Item2 = (props: itemProps): JSX.Element => {
  return (<div/>)
}

codesandbox sample

但得到警报

TS2739: Type 'OverridableComponent<BoxTypeMap<{}, "div">>' is 
missing the following properties from type
 'ReactElement<any, any>': type, props, key

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

你可能需要一个 ReactElement 或 ReactNode 作为类型。请参阅When to use JSX.Element vs ReactNode vs ReactElement? 了解何时使用哪个。

【讨论】:

  • 如果答案在该问题中,请投票以重复关闭而不是发布多余的答案。 (我不确定这个问题是否能回答这个问题,但如果是这样,那就是该做的。)
  • 不完全是,但我认为有足够的副本来保证这一点。我标记了它。
  • 感谢您的回答。 ReactNode 工作正常。
猜你喜欢
  • 2014-01-20
  • 2019-12-14
  • 2019-08-30
  • 2017-08-22
  • 1970-01-01
  • 2014-08-13
  • 2022-06-22
  • 1970-01-01
  • 2021-08-04
相关资源
最近更新 更多