reactjs - 如何使用 typescript 扩展react-bootstrap组件?

标签 reactjs typescript react-bootstrap

我正在使用 react-bootstrap@1.0.0-beta.14 并且我正在尝试使用react-bootstraps Button< 创建自定义 Button 组件,添加另一个 Prop ,isLoading。 由于react-bootstrap类型的定义方式,我最终导入了一些帮助器类型并复制了react-bootstrap类型的一部分:

import React from 'react'
import { Button as Btn, ButtonProps } from 'react-bootstrap'
import { BsPrefixProps, ReplaceProps } from 'react-bootstrap/helpers'

interface Props {
  isLoading?: boolean
}

type BtnProps<As extends React.ElementType = 'button'> = ReplaceProps<
  As,
  BsPrefixProps<As> & ButtonProps
>

export const Button: React.FC<BtnProps & Props> = ({ isLoading, disabled, ...props }) => {
  return <Btn {...props} disabled={isLoading || disabled} />
}

几乎有效。我得到的错误告诉我 ref prop 类型是错误的:

Types of property 'ref' are incompatible.

...

Type '(instance: HTMLButtonElement | null) => void' is not assignable to type '(instance: Button> | null) => void'.

我删除了大部分错误消息以获取相关位。 我需要将组件包装在forwardRef 中才能完成这项工作吗?

最佳答案

您可以在以下代码段中看到更好的方法。

import React from 'react';
import { Button, ButtonProps } from 'react-bootstrap'

interface PropType extends ButtonProps {
    buttonText: string;
    isSubmitting: boolean;
}

export const SubmitButton: React.FC<PropType> = (props: PropType) => {
let { isSubmitting, buttonText, ...remainingProps } = props;
    return (
        <Button  variant="primary" type="submit" disabled={props.isSubmitting} style={{margin: 10}} {...remainingProps}>
            {props.buttonText}
        </Button>
    )
}

关于reactjs - 如何使用 typescript 扩展react-bootstrap组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60297772/

相关文章:

javascript - 如何设计一个每秒都需要变化的 reducer ?

javascript - react 组件已卸载

javascript - angular2 - 服务值(value)不变

javascript - 在react bootstrap中编辑时在选择字段中显示变量的内容

reactjs - 自定义 React-Bootstrap 弹出窗口

css - 着色下拉菜单

javascript - 有没有办法结合 Webpack 模块来减小文件大小?

javascript - Redux-Form 可重复字段

typescript - 如何使用 typescript 中的接口(interface)映射 DTO?

angular - 三人组 : Draw elbow with begin radius and end radius