react如何设置样式
内联样式
在React中,内联样式通过对象形式设置,样式属性名采用驼峰命名法。例如设置一个红色背景的div:
<div style={{ backgroundColor: 'red', padding: '20px' }}>内联样式示例</div>
样式表文件
创建单独的CSS文件,通过import引入。例如创建styles.css:
.my-class {
background-color: blue;
color: white;
}
在组件中引入并使用:
import './styles.css';
function App() {
return <div className="my-class">样式表示例</div>;
}
CSS Modules
避免类名冲突,使用CSS Modules。创建styles.module.css:
.error {
color: red;
}
在组件中使用:
import styles from './styles.module.css';
function App() {
return <div className={styles.error}>CSS Modules示例</div>;
}
Styled-components
使用第三方库styled-components,安装后:
import styled from 'styled-components';
const StyledDiv = styled.div`
background-color: green;
color: white;
`;
function App() {
return <StyledDiv>Styled-components示例</StyledDiv>;
}
动态样式
根据状态动态改变样式:
function App() {
const [isActive, setIsActive] = useState(false);
return (
<div
style={{
color: isActive ? 'red' : 'black',
fontWeight: isActive ? 'bold' : 'normal'
}}
onClick={() => setIsActive(!isActive)}
>
点击切换样式
</div>
);
}
全局样式
在根组件中引入全局样式文件,或在index.js中直接引入:
import './global-styles.css';
或使用createGlobalStyle(styled-components):

import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
}
`;
function App() {
return (
<>
<GlobalStyle />
<OtherComponents />
</>
);
}






