JavaScript教程:React中使用css样式的5种方式

react中的样式方法
1. 行内样式
class App extends React.Component {
// ...
render() {
return (
<div style={{ background: '#eee', width: '200px', height: '200px'}}>
<p style= {{color:'red', fontSize:'40px'}}>行内样式</p>
</div>
)
}
}
2.声明样式
class App extends React.Component {
//...
const style1={
background:'#eee',
width:'200px',
height:'200px'
}
const style2={
color:'red',
fontSize:'40px'
}
render() {
return (
<div style={style1}>
<p style= {style2}>行内样式</p>
</div>
)
}
}
3. 引入样式
// css
.person{
width: 60%;
margin:16px auto;
border: 1px solid #eee;
box-shadow: 0 2px 3px #ccc;
padding:16px;
text-align: center;
}
// js
import React from 'react';
import './Person.css';
class App extends React.Component {
//....
render() {
return (
<div className='person'>
<p>person:Hello world</p>
</div>
)
}
}
export default App;
4.CSS Modules
// xxx.module.css
.person{
width: 60%;
margin:16px auto;
border: 1px solid #eee;
box-shadow: 0 2px 3px #ccc;
padding:16px;
text-align: center;
}
// js
import React, { Component } from 'react';
//局部样式
import styles from './Person.module.css';
//全局样式
import '../App.css'
class App extends Component {
render() {
return (
<div className={styles.person}>
<p className='fz'>person:Hello world</p>
</div>
)
}
}
}
5.Styled Components
// 依赖 npm install --save styled-components // 创建一个 Title 组件,它将渲染一个附加了样式的 <h1> 标签 const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; // 创建一个 Wrapper 组件,它将渲染一个附加了样式的 <section> 标签 const Wrapper = styled.section` padding: 4em; background: papayawhip; `; // 就像使用常规 React 组件一样使用 Title 和 Wrapper render( <Wrapper> <Title> Hello World! </Title> </Wrapper> }
相关推荐
-
「nginx」十、nginx的location配置详解2026-07-04 00:51:45 -

最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代
最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代2026-07-04 00:21:47 -
PHP读取Excel内的图片2026-07-03 00:07:41 -
mysql:Otter跨机房数据同步(单向)2026-07-03 00:02:48 -

在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境
在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境2026-07-02 00:15:08