限制Bootstrap仅适用于特定的React组件。

huangapple go评论71阅读模式
英文:

Restrict Bootstrap to specific React Components only

问题

我正在开发一个React应用程序,在其中我需要在一个组件中使用Bootstrap。但是Bootstrap被应用到了每个组件上,所有之前已经样式化的组件都被干扰了。这是因为在React中,CSS是全局应用的,这是有道理的。有没有一种方法可以解决这个问题?

(*注意:
我知道有一个技巧,可以将所有对"bootstrap.scss"文件的导入包装到一个局部类中,然后重新编译Bootstrap文件。但是,在包装之后,当我在Bootstrap的根目录中运行npm install时,它抛出了很多错误和弃用警告。*如果这个技巧对您有效,我会感激您给我提供已编译的源代码。)

英文:

I'm working on a react app where I need to make use of bootstrap for one of the components. But bootstrap is getting applied to every component and all the previously styled components are getting disturbed. This makes sense as CSS is globally applied in React. Is there a way to achieve this?

(Note:
I know there is one trick where we can wrap all the imports of the "bootstrap.scss" file into a local class and re-compile the bootstrap file. But after wrapping, when I hit npm install in the root directory of bootstrap, it threw so many errors and depreciation warnings.
In case if this trick is working for you, I would appreciate if you drop me the compiled source code.)

答案1

得分: 1

为了在React中仅将Bootstrap样式应用于特定组件,您可以考虑使用CSS模块。这个特性允许您在组件内以本地化的方式使用类名,从而防止样式泄漏到其他组件。

这个过程涉及在CSS模块中导入Bootstrap样式,然后在所需的组件中专门使用它们。以下是如何实现这一点的简单示例:

// MySpecificComponent.module.css
@import "~bootstrap/dist/css/bootstrap.min.css";

// MySpecificComponent.js
import React from 'react';
import styles from './MySpecificComponent.module.css';

function MySpecificComponent() {
  return (
    <div className={styles['container']}>
      <button className={styles['btn']}>A Button</button>
    </div>
  );
}

export default MySpecificComponent;
英文:

In order to apply Bootstrap styles to only a specific component in React, you might consider using CSS Modules. This feature essentially lets you utilize class names in a localized manner within your component, thereby preventing style leakage to other components.

The process would involve importing Bootstrap styles within a CSS module and then exclusively utilizing them within the desired component. Here's a simple demonstration of how you could implement this:

// MySpecificComponent.module.css
@import &quot;~bootstrap/dist/css/bootstrap.min.css&quot;;

// MySpecificComponent.js
import React from &#39;react&#39;;
import styles from &#39;./MySpecificComponent.module.css&#39;;

function MySpecificComponent() {
  return (
    &lt;div className={styles[&#39;container&#39;]}&gt;
      &lt;button className={styles[&#39;btn&#39;]}&gt;A Button&lt;/button&gt;
    &lt;/div&gt;
  );
}

export default MySpecificComponent;

huangapple
  • 本文由 发表于 2023年5月26日 13:21:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定