首页 > 解决方案 > 在无状态函数中包装的 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>>>'.

有任何想法吗?

标签: reactjstypescriptreact-bootstrap

解决方案


我不太精通使用打字稿,但从它的外观来看,您可以使用以下内容来允许可选道具。

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>
  );
}

希望这可以帮助!


推荐阅读