react中如何使用style
在React中使用style
React中可以通过内联样式或CSS类名来应用样式。以下是几种常见的方法:
内联样式
内联样式通过JavaScript对象传递,属性名采用驼峰命名法:
const divStyle = {
color: 'blue',
backgroundColor: 'lightgray',
padding: '10px'
};
function MyComponent() {
return <div style={divStyle}>Styled with inline style</div>;
}
CSS类名
使用className属性引用外部CSS文件中的类:
/* styles.css */
.my-style {
color: red;
font-size: 16px;
}
import './styles.css';
function MyComponent() {
return <div className="my-style">Styled with CSS class</div>;
}
CSS Modules
CSS Modules提供局部作用域的样式,避免类名冲突:
/* MyComponent.module.css */
.error {
color: red;
}
import styles from './MyComponent.module.css';
function MyComponent() {
return <div className={styles.error}>Styled with CSS Module</div>;
}
styled-components
使用第三方库styled-components创建带样式的组件:
import styled from 'styled-components';
const StyledButton = styled.button`
background: palevioletred;
color: white;
padding: 0.5rem 1rem;
`;
function MyComponent() {
return <StyledButton>Styled Button</StyledButton>;
}
动态样式
根据props或state动态改变样式:
function MyComponent({ isActive }) {
const dynamicStyle = {
color: isActive ? 'green' : 'gray',
fontWeight: isActive ? 'bold' : 'normal'
};
return <div style={dynamicStyle}>Dynamic Style</div>;
}
样式库
使用第三方UI库如Material-UI、Ant Design等提供的样式系统:
import { Button } from '@material-ui/core';
function MyComponent() {
return <Button variant="contained" color="primary">Material-UI Button</Button>;
}






