gpt4 book ai didi

css - react / typescript : Idiomatic code for custom components that merge attributes?

转载 作者:行者123 更新时间:2023-11-28 15:18:13 25 4
gpt4 key购买 nike

版本:Typescript 2.3、React 16、Bootstrap 4。

我有一个可行的解决方案,如下所述,它涉及导入另一个外部库来完成此操作。我觉得必须有一个标准的解决方案来合并自定义组件的属性,但是使用 classnames包是我想出的唯一方法。

编写自定义 AppButton我的应用程序组件,我想要一个默认样式,但允许覆盖。

第一个版本看起来像:

export interface AppButtonProps 
extends ButtonHTMLAttributes<HTMLButtonElement>{
}
export class AppButton
extends React.PureComponent<AppButtonProps, object> {
render(){
return <button
{...this.props}
className="btn btn-primary"
/>;
}
}

与这样的代码一起使用,以覆盖按钮的颜色:

<AppButton type="submit" className="btn-success">Do the thing</AppButton>

但这不起作用,取决于 <button> 的顺序属性,你要么得到一个按钮 btn btn-primarybtn-success - 但我想要的是 btn btn-success .

我目前的方法使用 classnames包裹:

export class AppButton
extends React.PureComponent<AppButtonProps, object> {
render(){
return <button
{...this.props}
className={classNames("btn", "btn-primary", this.props.className)}
/>;
}
}

只有某种有效,结果是btn btn-primary btn-success ,就合并属性而言,这并不是我想要的,但在这种特定情况下它可以正确显示 - 我猜是因为 Bootstrap 更喜欢 btn-successbtn-primary .

我能看到的获得我需要的确切样式的唯一明显解决方案是解析和扫描传入的 props.style btn-* 的属性并且只添加 btn-primary如果不存在。

因此,问题是:Typescript、React 或 Bootstrap 中是否有内置实用程序可以解决此问题?或者也许我想要一些其他包裹?

或者也许这实际上是错误的方法,我应该在 AppButtonProps 中编写自己的自定义属性并编写一堆样式逻辑?

最佳答案

我建议使用 defaultProps如果没有提供其他值,则使用 btn-primary 作为默认类:

export interface AppButtonProps 
extends ButtonHTMLAttributes<HTMLButtonElement>{
}
export class AppButton
extends React.PureComponent<AppButtonProps, object> {
static defaultProps = {
className: "btn-primary",
};
render(){
return <button
{...this.props}
className={classNames("btn", this.props.className)}
/>;
}
}

根据您在下面的评论,您还可以为决定按钮主要外观的类添加一个单独的 Prop :

export interface AppButtonProps 
extends ButtonHTMLAttributes<HTMLButtonElement>{
mainButtonClass?: string;
}
export class AppButton
extends React.PureComponent<AppButtonProps, object> {
static defaultProps = {
mainButtonClass: "btn-primary",
};
render(){
return <button
{...this.props}
className={classNames("btn", this.props.mainButtonClass, this.props.className)}
/>;
}
}

关于css - react / typescript : Idiomatic code for custom components that merge attributes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46701244/

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