【问题标题】:Reusing React components with different styling重用具有不同样式的 React 组件
【发布时间】:2018-04-20 12:56:30
【问题描述】:

为了尽量保持 React 代码的可重用性,我经常将 CSS 类作为 React 组件中的属性传递。这样做的用例是这些组件的功能完全相同,但根据它们在页面中的位置可能看起来不同。

是否可以将 CSS 类作为属性传递给 React 组件,或者是否有更好的方法来完成上述用例?

快速、简化的示例:

const ToolTipButton = ({ buttonClass, onButtonClick, children }) => (
  <button
    className={buttonClass}
    onClick={onButtonClick}
    data-toggle="pages-tooltip"
    data-placement="top"
    title="Do Something"
  >
    {children}
  </button>
);

<ToolTipButton buttonClass={'ButtonClass1'} onButtonClick={this.doesSomething}/>
<ToolTipButton buttonClass={'ButtonClass2'} onButtonClick={this.doesSomething}>
  // Text and other stuff
</ToolTipButton>

【问题讨论】:

  • Styled Components 采用了类似的方法。我建议检查一下。
  • 几乎所有已构建的组件,无论是语义、引导程序等...通常都有一个组件接受的 className 属性。

标签: javascript css reactjs twitter-bootstrap-3 components


【解决方案1】:

Css 选择器是可链接的,因此只需使用纯 CSS,您就可以根据容器拥有单独的样式。按钮组件可以有一个静态类,例如tool-tip-button,并使其样式表作用于包含的组件。例如

.tool-tip-button {
  color: black;
}

.component-a .tool-tip-button {
   color: green;
}

.component-b .tool-tip-button {
   color: red;
}

请注意,React 组件可以(并且建议)拥有自己的单独样式表,例如ComponentA.cssComponentB.css,然后简单地导入它们:

// ComponentA.js
import './ComponentA.css'

【讨论】:

    【解决方案2】:

    只要您的类定义在范围内,将类名作为道具传递是完全可以接受的。在类定义不在范围内的情况下,另一种方法是传递样式定义对象。例如:

    const ToolTipButton = ({ style, onButtonClick, children }) => (
      <button
        style={style}
        onClick={onButtonClick}
        data-toggle="pages-tooltip"
        data-placement="top"
        title="Do Something"
      >
        {children}
      </button>
    );
    
    <ToolTipButton style={{backgroundColor: 'red'}} onButtonClick={this.doesSomething}/>
    

    一些组件库(例如 Material UI)允许您将类名和样式定义对象作为道具传递。一般来说,如果可能的话,最好只使用一个类名(以避免在你的 js 中定义样式)。

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 1970-01-01
      • 2022-12-13
      • 2020-08-14
      • 2021-02-10
      • 2022-06-24
      • 2019-03-03
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多