【发布时间】: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