react如何加style
React 中添加样式的方法
在 React 中,可以通过多种方式为组件添加样式。以下是常见的几种方法:
内联样式
内联样式直接通过 style 属性传递给组件,使用 JavaScript 对象表示样式规则,属性名采用驼峰命名法。
const MyComponent = () => {
return (
<div style={{ color: 'red', fontSize: '16px' }}>
Hello, World!
</div>
);
};
CSS 类名
通过 className 属性引用外部 CSS 文件或模块化 CSS 中的类名。
// App.css
.myClass {
color: blue;
font-size: 18px;
}
// App.jsx
import './App.css';
const MyComponent = () => {
return <div className="myClass">Hello, World!</div>;
};
CSS Modules
使用 CSS Modules 可以避免类名冲突,生成的类名是唯一的。
// styles.module.css
.container {
background-color: #f0f0f0;
}
// Component.jsx
import styles from './styles.module.css';
const MyComponent = () => {
return <div className={styles.container}>Hello, World!</div>;
};
Styled-components
使用 styled-components 库可以在 JavaScript 中直接编写 CSS。
import styled from 'styled-components';
const StyledDiv = styled.div`
color: green;
font-size: 20px;
`;
const MyComponent = () => {
return <StyledDiv>Hello, World!</StyledDiv>;
};
动态样式
根据组件状态或属性动态调整样式。
const MyComponent = ({ isActive }) => {
const style = {
color: isActive ? 'red' : 'black',
fontWeight: isActive ? 'bold' : 'normal'
};
return <div style={style}>Hello, World!</div>;
};
全局样式
通过 createGlobalStyle(styled-components)或直接在 index.css 中定义全局样式。
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
`;
const App = () => {
return (
<>
<GlobalStyle />
<MyComponent />
</>
);
};
第三方 UI 库
使用如 Material-UI、Ant Design 等库时,可以直接使用其提供的样式组件或主题系统。
import { Button } from '@mui/material';
const MyComponent = () => {
return <Button variant="contained">Click Me</Button>;
};
以上方法可以根据项目需求和个人偏好灵活选择。







