【问题标题】:Dynamic react component type with Link as type以 Link 为类型的动态反应组件类型
【发布时间】:2022-11-10 19:06:18
【问题描述】:

我正在努力输入以下可以处理链接或 onClick 事件的动态按钮组件。这是我现在尝试重构为 TypeScript 的组件的简化 sn-p。

import React from 'react'
import { Link } from 'react-router-dom'

type Props = {
  children: React.ReactNode,
} & (
  {
    to: string,
    type: undefined,
    onClick: undefined,
  } | {
    to: undefined,
    type: 'button' | 'submit',
    onClick: (event: React.MouseEvent<HTMLButtonElement>) => void,
  }
)

export default function Button(props: Props) {
  const { children, to } = props
  const TagName = to ? Link : 'button'
  return (
    <TagName {...props}>
      {children}
    </TagName>
  )
}

它给了我以下错误:

Type '{ children: ReactNode; to: string; onClick: undefined; } | { children: ReactNode; to: undefined; onClick: (event: MouseEvent<HTMLButtonElement, MouseEvent>) => void; }' is not assignable to type 'IntrinsicAttributes'.
  Type '{ children: ReactNode; to: string; onClick: undefined; }' has no properties in common with type 'IntrinsicAttributes'.

我想我必须定义 TagName 的类型,但我无法确定正确的类型。有什么建议吗?

这是导致问题的 Link 组件类型,因为没有它我可以让它工作。

【问题讨论】:

    标签: reactjs typescript react-router-dom


    【解决方案1】:

    为处理未定义值的可选属性添加?

    type Props = {
      children: React.ReactNode,
      to?: string,
      onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void,
    
    } 
    

    【讨论】:

    • 是的,我知道,但组件使用 XOR 模式。不允许同时设置 to 和 onClick 属性。
    • 将类型更改为接口
    猜你喜欢
    • 2022-01-09
    • 2019-01-08
    • 2023-03-14
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多