我希望组件根据给定的特定道具的值接受不同的道具。类似于以下内容。
const Button: React.FC<TButton> = ({ href, children, ...rest }) => {
if (href) {
return <a href={href} {...rest}>{children}</a>
}
return <button {...rest}>{children}</button>
}
type TButton = { href: string & IAnchor } | { href: undefined & IButton }
interface IAnchor extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}
interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {}
事情是,无法弄清楚如何正确地解决这个问题。我的意思是,似乎条件没有被正确解析或解释。
如果您想进一步了解该问题,请参考此StackBlitz。
看来您实质上是在尝试使用有区别的联合。但似乎它不起作用...rest
。所以要使其工作
向两个接口添加其他属性,例如type
将其用作判别式
interface IAnchor extends React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement> {
type: 'anchor'
href: string
}
interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {
type: 'button'
}
porps
在条件分支中接受并销毁它们
const Button: React.FC<TButton> = (props): JSX.Element => {
if (props.type === 'anchor') {
const { type, href, children, ...rest } = props;
return (
<a href={href} {...rest}>
{children}
</a>
)
}
const { type, children, ...rest } = props;
return <button {...rest}>{children}</button>
}
参见工作示例
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句