reactjs - 无法将解构的道具分配给 react-bootstrap 组件
问题描述
我已经安装了react-bootstrap并想为我的项目自定义默认按钮,这样我就可以简单地编写大多数按钮<Button>
而无需任何variant
选项。
import * as bs from "react-bootstrap";
export const Button: bs.Button = ({
variant = "outline-secondary",
...props
}) => {
return <bs.Button variant={variant} {...props} />;
};
这会导致以下错误。
/path/to/MyComponent.tsx(11,11) 中的 TypeScript 错误:
Type '{ variant: string; } & Pick<PropsWithChildren<ReplaceProps<As, BsPrefixProps & ButtonProps>>, "slot" | ... 262 更多... | Exclude<...>>' 不可分配给类型 'IntrinsicAttributes & Pick<ComponentPropsWithRef, Exclude<keyof ComponentPropsWithRef, "slot" | ... 262 更多... | "onTransitionEndCapture">> & BsPrefixProps<...> & ButtonProps & { ...; }'。
输入'{变体:字符串;} & Pick<PropsWithChildren<ReplaceProps<As, BsPrefixProps & ButtonProps>>, "slot" | ... 262 更多... | Exclude<...>>' 不能分配给类型 'Pick<ComponentPropsWithRef, Exclude<keyof ComponentPropsWithRef, "
如果我在不解构的情况下编写它,它的工作原理就很简单。
export const Button: bs.Button = (props) => {
return (
<bs.Button {...props} variant={props.variant || "outline-secondary"} />
);
};
为什么第一个不起作用?什么从props
?
更新
版本:TypeScript 4.0.2、React 16.13.1、React Bootstrap 1.3.0
解决方案
你快到了。
您的代码不起作用,因为您没有声明道具的类型,所以您只需要这样做:
const ButtonX: bs.Button = ({
variant = "outline-secondary",
...props
// Here´s the secret - a set props as bootstrap ButtonProps type
}: bs.ButtonProps) => {
return <bs.Button variant={variant} {...props} />;
};
推荐阅读
- kubernetes - 无法将日志发送到 Graylog kubernetes
- sql-server - 为什么 SQL 内连接称为内连接,外连接称为外连接?
- java - 使用 Android 的媒体播放器处理播放声音
- javascript - 如何修复由内联中断引起的“无效或意外令牌”?
- python - ImportError:无法导入名称“RandomizedLogisticRegression”
- java - 在 nativescript 中编写 java 文件以使用本地 java lib
- html - CSS 和 Bootstrap:创建一条连接行的线
- react-native - 无法使用 react-native-calendars
- ubuntu - 在 Ubuntu 19.04 上安装 Redis-Commander 作为服务
- c - C 编程指针和数组