react样式处理有两种处理方式:
- 行内样式处理
- 使用className来定义类名
使用行内样式处理:
语法:
<元素 style={ {css属性1:值1, css属性2:值2} }></元素>
用法:
// 引入react核心包
import React from 'react'
// 设计DOM来渲染的一个包
import ReactDom from 'react-dom'
const ele = (
<div
style={{
width: 100,
height: '100px',
backgroundColor: 'gold',
textAlign: 'center',
lineHeight: '100px'
}}
>
吃水不忘挖井人
</div>
)
// 渲染谁,渲染到哪里
ReactDom.render(ele, document.querySelector('#root'))
注意点:
- 有两个
{{ }}
,外层的{}
表示要开始写 JSX 表达式了,内层的{}
表示是一个对象。 - 属性名是小驼峰格式,例如
background-color
需要写成backgroundColor
- 属性值是字符串,如果单位是 px,可以简写成数值
类名更改样式
- 使用 className 定义类名
css代码: 定义css文件 index.css
.box{
width: 100px;
height: 100px;
margin: 0 auto;
line-height: 100px;
background-color: #d2dd2d;
text-align: center;
}
js代码:
// 引入react核心包
import React from 'react'
// 设计DOM来渲染的一个包
import ReactDom from 'react-dom'
// 导入自己定义路径的css文件
import './index.css'
const ele = <div className="box">晓看天色暮看云</div>
// 渲染谁,渲染到哪里
ReactDom.render(ele, document.querySelector('#root'))