gpt4 book ai didi

reactjs - React + Material-UI + Typescript : Inherit props from button to add different variants

转载 作者:行者123 更新时间:2023-12-05 04:00:06 24 4
gpt4 key购买 nike

我想扩展默认的 Material-UI 按钮以添加更多变体,例如“方形”。

如何定义 prop 接口(interface)来继承/组合 props。

这是我的代码:

import React from "react";
import { Button as MuiButton } from "@material-ui/core";
import { ButtonProps as MuiButtonProps } from "@material-ui/core/Button";

interface ButtonProps extends MuiButtonProps {
variant?: "square";
}

const defaultProps = {};

const Button: React.FC<ButtonProps> = ({variant, children, ...props}) => {
return (
<MuiButton variant={variant} {...props}>
{props.children}
</MuiButton>;
)
};

Button.defaultProps = defaultProps;

export default Button;

理想情况下,我想像这样使用这个组件:

<ExtendedButton href="/" variant="square">Click Me!</ExtendedButton>

最佳答案

TYpeScript 不允许在扩展接口(interface)时覆盖属性。因此,您应该首先从 MuiButtonProps 中排除属性,然后在 ButtonProps 中重新定义它。

import React from "react";
import { Button as MuiButton } from "@material-ui/core";
import { ButtonProps as MuiButtonProps } from "@material-ui/core/Button";

interface ButtonProps extends Pick<MuiButtonProps, Exclude<keyof MuiButtonProps, "variant">> {
variant?: "square" | MuiButtonProps["variant"];
}

使用 PickExclude 的属性排除适用于 TypeScript 3.5 及以下到 2.8。你可能会看到 another options根据您使用的 TypeScript 版本排除属性。

并且当您希望扩展现有属性 variant 的当前类型时,您可以使用索引访问运算符来获取原始 variant 属性的类型,以将其与其他 合并>“方形” 类型。

关于reactjs - React + Material-UI + Typescript : Inherit props from button to add different variants,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com