繁体   English   中英

包装 react-bootstrap 组件 Typescript 错误

[英]Wrapping a react-bootstrap component Typescript error

我正在尝试围绕 Bootstrap 的Alert组件创建一个包装器组件。

Alert组件上有LinkHeading属性,因此您可以执行<Alert.Link> - 请参阅https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Alert.js#L119

import React from 'react';
import BootstrapAlert, { AlertProps } from 'react-bootstrap/Alert';

const Alert = (props: AlertProps) => {
  return <BootstrapAlert bsPrefix="my-app-alert" {...props} />;
};

export default Alert;

当我渲染时:

<Alert variant='primary'>
  Hello 
  <Alert.Link href="#">world</Alert.Link>
</Alert>

我收到 Typescript 错误:

Property 'Link' does not exist on type '(props: AlertProps) => Element'.ts(2339)

您需要将Alert.LinkAlert.Heading组件从 bootstrap 的 alert 命名空间复制到您的自定义Alert组件中。

import React from 'react';
import BootstrapAlert, { AlertProps } from 'react-bootstrap/Alert';

const Alert = (props: AlertProps) => {
  return <BootstrapAlert bsPrefix="my-app-alert" {...props} />;
};

// Copy the Heading and Link components from Bootstrap as well
// You might need to declare the Heading and Link properties on your Alert type too
Alert.Heading = BootstrapAlert.Heading;
Alert.Link = BootstrapAlert.Link;

export default Alert;

如果你查看react-bootstrap/src/Alert.js的源代码,你可以看到他们是如何定义他们的 Alert 命名空间的:

// Define the Alert component
const Alert = React.forwardRef((uncontrolledProps, ref) => {
    //...implementation
});

// Then at the bottom of the file they add the `Alert.Link` and
// `Alert.Heading` properties to the component:

Alert.Link = createWithBsPrefix('alert-link', {
  Component: SafeAnchor,
});

Alert.Heading = createWithBsPrefix('alert-heading', {
  Component: DivStyledAsH4,
});

export default Alert;

这就是为您提供 react-bootstrap API 的原因:

// Standard react-bootstrap usage
import { Alert } from 'react-bootstrap/Alert';

<Alert>
    <Alert.Heading>My alert heading</Alert.Heading>
    <Alert.Link>My link content</Alert.Link>
</Alert>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM