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

标签 css twitter-bootstrap reactjs typescript

版本: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/

相关文章:

html - 当我尝试重复 x 图像 Sprite 时,它会显示整个图像

javascript - 使用 jQuery 的 Bootstrap 错误警报

php - 有条件地加载css文件

reactjs - 将 Prop 传递给 redux

javascript - 防止浏览器缓存 JavaScript 文件的更好方法

css - 如何使下拉菜单与标题左侧对齐?

css - 使用缩放元素跨浏览器居中

html - 停止 Bootstrap3 按钮文本以在鼠标悬停时打开下划线

javascript - 需要建议 : How to properly connect React to MongoDB

javascript - Next.js 生产失败但开发工作正常