在 react 中,引入 CSS 不如 Vue 方便简洁,其引入 css 的方式有很多种,各有利弊。本文将介绍 React 中引入 CSS 的 4 种方式以及它们的特点。
1. 内联样式
React 允许在组件内部使用 JavaScript 对象的形式定义样式,然后将其分配给组件的 style 属性。这是一种内联样式的方式,它的主要特点是:
-
样式信息与组件紧密绑定,易于维护。
-
样式在组件的 JavaScript 文件中定义,避免了全局作用域的样式冲突。
import React from 'react';
const MyComponent = () => {
const styles = {
backgroundColor: 'lightblue',
color: 'darkblue',
};
return (
<div style={styles}>
This is a component with inline styles.
</div>
);
};
export default MyComponent;
2. 模块化CSS
另一种流行的方式是使用模块化 CSS ,通常与CSS模块、Styled-components 或 Emotion 等库一起使用。这种方式的特点包括:
-
样式文件被组件范围化,不会影响其他组件的样式。
-
可以使用CSS的所有功能,如嵌套、变量等。
// styles.module.css
.myComponent {
background-color: lightblue;
color: darkblue;
}
// MyComponent.js
import React from 'react';
import styles from './styles.module.css';
const MyComponent = () => {
return (
<div className={styles.myComponent}>
This is a component with module CSS.
</div>
);
};
export default MyComponent;
3. 全局 CSS
还可以像普通的 HTML 应用程序一样引入全局 CSS 文件。这种方式的特点是:
-
所有组件共享同一个全局样式。
-
可以使用现有的CSS库和工具,如Bootstrap。
// styles.css
.myComponent {
background-color: lightblue;
color: darkblue;
}
// MyComponent.js
import React from 'react';
const MyComponent = () => {
return (
<div className="myComponent">
This is a component with global CSS.
</div>
);
};
export default MyComponent;
4. CSS-in-JS
最后一种方式是使用 CSS-in-JS 库,如 Styled-components 或 Emotion。这种方式的特点包括:
-
样式与组件直接关联,无需额外的样式文件。
-
允许在JavaScript中编写样式,具有更高的灵活性。
import React from 'react';
import styled from 'styled-components';
const StyledDiv = styled.div`
background-color: lightblue;
color: darkblue;
`;
const MyComponent = () => {
return (
<StyledDiv>
This is a component with CSS-in-JS.
</StyledDiv>
);
};
export default MyComponent;
如何选择
内联样式适用于简单的组件,模块化CSS适用于需要局部样式的组件,全局CSS适用于全站样式的定义,而CSS-in-JS适用于需要更高可维护性和灵活性的场景。
无论你选择哪种方式,都应该在保持代码整洁和可维护性的前提下,确保应用程序的样式一致性和性能。
希望本文对您有所帮助!