reactjs - 不能将 href 与 IconButtonProps 一起使用
问题描述
我正在尝试为 IconButton 创建一个包装器。我希望能够传递例如组件或 href 道具,但是在将 IconButtonProps 传递给它时我无法做到这一点。我怎么能做到这一点?
function NavIconLink(props : IconButtonProps) {
const classes = useStyles();
const { ...rest } = props;
return (
<IconButton
{...rest}
href=""
className={classes.buttonLink}
>
{props.children}
</IconButton>
)
}
解决方案
解决方案
将类型上的组件类型的泛型设置IconButtonProps
为'a'
。
function NavIconLink(props: IconButtonProps<'a'>) {
解释
我能够复制您的错误。如果我只是设置一个href
没有任何问题。但是,如果我设置href
并传递所有内容,...rest
那么我会收到No overload matches this call.
错误消息。
错误跟踪很长,但这Overload 1 of 3
是我们要解决的部分。那就是你会看到错误的地方
属性“onCopy”的类型不兼容。
类型“
ClipboardEventHandler<HTMLButtonElement> | undefined
”不可分配给类型“ClipboardEventHandler<HTMLAnchorElement> | undefined
”。
简而言之,错误本质上是“您将href
道具设置为好像元素是 an HTMLAnchorElement
,但其他道具是用于 an HTMLButtonElement
”。
我们需要确保所有的 props 都是正确的类型HTMLAnchorElement
。
如果您查看该IconButtonProps
类型的源代码,您会发现它有一个D
指定元素的泛型类型参数。
export type IconButtonProps<
D extends React.ElementType = IconButtonTypeMap['defaultComponent'],
P = {}
> = OverrideProps<IconButtonTypeMap<P, D>, D>;
您还将看到默认值为D
--button
这就是您收到HTMLButtonElement
错误消息的原因。
export type IconButtonTypeMap<
P = {},
D extends React.ElementType = 'button'
> = ExtendButtonBaseTypeMap<{
props: P & {
...
};
defaultComponent: D;
...
}>;
所以当你使用这种类型时,你需要指定你的...rest
props 应该是一个a
组件而不是一个button
. 将第一个泛型设置IconButtonProps
为'a'
,您的错误将消失。
function NavIconLink({ children, ...rest } : IconButtonProps<'a'>) {
return (
<IconButton
{ ...rest } // props for a link
href="" // also a prop for a link
>
{children}
</IconButton>
)
}
推荐阅读
- python - 如何使用 selenium python 访问隐藏的 Instagram 按钮
- python-3.x - 从抓取的文本中提取非结构化地址和电子邮件 ID 作为变量 - Python
- reactjs - 使用 setState Hook 根据 React JS 中的一组条件更新先前的值
- flutter - 无法在真实设备上调试 Flutter 应用程序在模拟器上运行良好
- spring-boot - 我的休息控制器没有从 URL 调用
- docker - 复制失败 '/target/x86_64-unknown-linux-musl/release/microservice_app: no such file or directory' Rust Dockerfile
- node.js - Socket.io Node Js 服务器和 React js 客户端未连接
- java - Android Volley:BasicNetwork.performRequest:意外响应代码 400
- node.js - 代理错误:无法将请求 /user/update 从 localhost:3000 代理到 http://localhost:5000
- python - 如何在 Tkinter 中将类/窗口从“普通”窗口转换为 Toplevel() 窗口?