英文:
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 "~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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论