reactjs - 在无状态函数中包装的 Bootstrap 组件的道具使用什么类型?
问题描述
我正在尝试将React Bootstrap组件封装在无状态函数中:
import React from "react"
import { Card } from "react-bootstrap"
export function MyComponent(props: ???) {
const { children, ...otherProps } = props;
return (
<Card>
<Card.Body {...otherProps}>{children}</Card.Body>
</Card>
)
}
我的问题:我应该使用什么道具???
?
我已经尝试提取React Bootstrap 类型定义的部分内容以得到以下结果:
export function MyComponent<As extends React.ElementType = 'div'>(props: ReplaceProps<As, BsPrefixProps<As>>) {
const { children, ...otherProps } = props;
return (
<Card>
<Card.Body {...otherProps}>{children}</Card.Body>
</Card>
)
}
但这给出了以下怪物错误消息:
No overload matches this call.
Overload 1 of 2, '(props: Readonly<ReplaceProps<As, BsPrefixProps<As>>>): CardBody<As>', gave the following error.
Type 'Pick<ReplaceProps<As, BsPrefixProps<As>>, "as" | "bsPrefix" | Exclude<Exclude<keyof ComponentPropsWithRef<As>, "as" | "bsPrefix">, "children">> & { ...; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<CardBody<As>> & Readonly<ReplaceProps<As, BsPrefixProps<As>>> & Readonly<...>'.
Type 'Pick<ReplaceProps<As, BsPrefixProps<As>>, "as" | "bsPrefix" | Exclude<Exclude<keyof ComponentPropsWithRef<As>, "as" | "bsPrefix">, "children">> & { ...; }' is not assignable to type 'Readonly<ReplaceProps<As, BsPrefixProps<As>>>'.
Overload 2 of 2, '(props: ReplaceProps<As, BsPrefixProps<As>>, context?: any): CardBody<As>', gave the following error.
Type 'Pick<ReplaceProps<As, BsPrefixProps<As>>, "as" | "bsPrefix" | Exclude<Exclude<keyof ComponentPropsWithRef<As>, "as" | "bsPrefix">, "children">> & { ...; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<CardBody<As>> & Readonly<ReplaceProps<As, BsPrefixProps<As>>> & Readonly<...>'.
Type 'Pick<ReplaceProps<As, BsPrefixProps<As>>, "as" | "bsPrefix" | Exclude<Exclude<keyof ComponentPropsWithRef<As>, "as" | "bsPrefix">, "children">> & { ...; }' is not assignable to type 'Readonly<ReplaceProps<As, BsPrefixProps<As>>>'.
有任何想法吗?
解决方案
我不太精通使用打字稿,但从它的外观来看,您可以使用以下内容来允许可选道具。
import React from "react";
import { Card } from "react-bootstrap";
type CardContainerProps = {
children: React.ReactNode;
as?: React.ElementType;
bsPrefix?: string;
}
export function MyComponent({ children, ...otherProps }: CardContainerProps) {
return (
<Card>
<Card.Body {...otherProps}>{children}</Card.Body>
</Card>
);
}
希望这可以帮助!
推荐阅读
- reactjs - 为什么尝试在变量中渲染组件时会出错?
- php - 如何用标签包装所有文本节点?
- macos-catalina - 卡特琳娜 USB 驱动器
- javascript - FileReader().readAsArrayBuffer(file) 结果在第一次加载文件后卡住
- validation - 需要有关使用 java 检查签名 pdf 的签名/证书的建议
- r - R中变量值的频率和直方图
- c - 带按钮的 LED 闪烁
- automation - 赛普拉斯 - 等待滚动调整大小
- graph - 图能否找到从一个顶点到另一个顶点在两个方向上的最短路径?
- javascript - Angular 7 注入指令作为提供者