在react中如何写内联样式
在 React 中写内联样式的方法
React 中可以通过 JavaScript 对象的形式定义内联样式,并通过 style 属性传递给组件。以下是几种常见的实现方式:
直接传递样式对象
<div style={{ color: 'red', fontSize: '16px' }}>
这是一段红色文字
</div>
使用变量存储样式对象
const myStyle = {
backgroundColor: 'lightblue',
padding: '10px',
borderRadius: '5px'
};
function MyComponent() {
return <div style={myStyle}>带样式的 div</div>;
}
动态样式
可以根据组件状态或属性动态调整样式:
function DynamicComponent({ isActive }) {
const dynamicStyle = {
color: isActive ? 'green' : 'gray',
fontWeight: isActive ? 'bold' : 'normal'
};
return <p style={dynamicStyle}>动态样式文本</p>;
}
注意事项
- React 内联样式属性名使用驼峰命名法(如
fontSize而非font-size) - 数值类属性默认单位为 px,可以直接写数字:
<div style={{ width: 100, height: 50 }} /> - 如需其他单位需要显式指定:
<div style={{ margin: '1rem' }} />
样式组合
可以通过展开运算符组合多个样式对象:
const baseStyle = { padding: 10 };
const highlightStyle = { backgroundColor: 'yellow' };
<div style={{ ...baseStyle, ...highlightStyle }}>
组合样式示例
</div>






