以下纪录在 React 中撰写 CSS 的几种方法。
style 属性内容除了传统 HTML 的字串写法外,
可以传入一个定义了 style 内容的 JavaScript object。
property 要改成 camelCase 写法,
与 DOM style JavaScript property 写法一致,
这样效率更高,并可防止 XSS 安全漏洞。
除了 zoom
、zIndex
等没有单位的属性外,
React 会替 value 为 number 的属性自动加上 px
,
如要指定其他单位,可以 string 来撰写,
浏览器引擎前缀除了 ms 外皆以大写字母开头
例如 WebkitTransition
。
行内样式范例:
<App>
<input type="text" style={{
baclgroungColor:"#f66",
fontSize: 15,
height: '10%'
}} />
</App>
在文件内建立一个样式物件,
然後使用 inline style 写法引入该物件
import React from 'react';
class Page extends React.Component{
render(){
let mystyle={
width:'200px',
height:'80px',
backgroundColor:'yellow',
fontSize:'24px',
textAlign:'center'
}
return(
<div style={mystyle}>This is Page1!</div>
);
}
}
export default Page;
引入外部 css文档後,
即可直接加上 class 属性来套用 css
import './style.css';
const App = () =>{
return (
<div className="wrap"> // 套用 style.css 中 .wrap 所定义的样式
我是网页内容
</div>
)
}
在 React 中,使用 CSS class
通常比 inline style 效能更好,
style 属性一般则被用作增加动态 style 的方式。
以下为可搭配 React 使用的 CSS 处理方案
可以随意命名 class,由套件协助处理
不用担心会重复或污染全局
import myStyle from './mystyle.module.scss'
className = { myStyle.title }
:global(.wrap){ color: green; background: red; }
className { color:green; background: red; } .otherClassName { compose: className; color: yellow; }
.otherClassName { compose: className from './another.css'; color: yellow; }
css-module 和 sass 结合使用
常用插件:
:root{ --mainColor: #ffc001; }
)React 预设不可拓展 webpack、babel 等套件,
使用 CRACO 即可自订这些套件
用 JavaScript 来写 CSS
使用方法:
style(Component)`
.styled-common-modal {
background: rgba(0,0,0,0.5) !important;
}
`
ES6 标签模板语法:
const Title = styled.myH1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`
<App>
<Title>我是标题,自带样式</Title>
</App>
CSS 嵌套语法:
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
> h2 {
color: palevioletred;
}
> .content{
width: 100%;
height: 200px;
}
`
拓展 css-component:
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`
const ExtendTitle = styled(Title)`
font-size: 1.8em;
backgroung-color: gray;
`
拓展 component 的 css:
const Link = ({ className, children }) => {
<a className={className}>
{children}
</a>
}
const StyledLink = styled(Link)`
color: palevioletred;
font-weight: bold;
`
<<: 不只懂 Vue 语法:试说明 computed 的 get 与 set 运作机制?
call, apply, bind 方法 当我们对函式使用 call, apply, bind 这三...
Day1 的时候有提到我们公司使用的云端方案是GCP (Google Cloud Platform)...
前言: 在Activity 和 Fragment 只要操作 xml 的元件,在 onCreate 时...
pull 一个 ubuntu image docker pull ubuntu:19.04 列出现有...
gsap.to()、gsap.from()和gsap.fromTo()定义了基本动画架构,除此之外,...