react样式如何设定
内联样式
在React中可以直接使用内联样式,通过JavaScript对象的形式传递样式。样式属性名需要使用驼峰命名法,例如backgroundColor而非background-color。
<div style={{ color: 'red', fontSize: '16px' }}>内联样式示例</div>
CSS样式表
创建单独的CSS文件,通过import引入到组件中。这种方式适合全局或可复用的样式。
/* styles.css */
.container {
padding: 20px;
background-color: #f0f0f0;
}
import './styles.css';
function App() {
return <div className="container">CSS样式表示例</div>;
}
CSS Modules
CSS Modules可以避免样式冲突,每个组件的样式都是局部的。文件名需以.module.css结尾。
/* Button.module.css */
.error {
color: white;
background-color: red;
}
import styles from './Button.module.css';
function Button() {
return <button className={styles.error}>CSS Modules示例</button>;
}
Styled Components
使用第三方库styled-components可以编写实际的CSS代码来样式化组件。
import styled from 'styled-components';
const StyledButton = styled.button`
background: palevioletred;
color: white;
font-size: 1em;
padding: 0.25em 1em;
`;
function Button() {
return <StyledButton>Styled Components示例</StyledButton>;
}
Tailwind CSS
通过实用工具类快速构建UI,需先安装配置Tailwind CSS。
<div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md">
Tailwind CSS示例
</div>
动态样式
根据组件状态或props动态调整样式。
function DynamicComponent({ isActive }) {
const style = {
color: isActive ? 'green' : 'gray',
fontWeight: isActive ? 'bold' : 'normal'
};
return <div style={style}>动态样式示例</div>;
}
样式优先级
React内联样式的优先级高于外部CSS,但会被!important覆盖。使用CSS Modules或Styled Components可更好管理样式作用域。
// 内联样式优先级示例
<div style={{ color: 'blue' }} className="red-text">蓝色生效</div>
/* 外部CSS */
.red-text {
color: red !important; /* 这会覆盖内联样式 */
}






