4.2-React+CSS
Create by fall on 5 Apr 2021 Recently revised in 14 Mar 2024
代码隔离
在文件名称的扩展名之前添加 module.
即可改变代码作用域,比如说在 less 中,通过module.less
实现代码隔离。
使用
React.lazy()
包裹的内容中,如果引入了module.less
等内容,则会自动打包生成文件。
CSS
Emotion
和 styled-components
一样,是社区中最流行的 CSS-in-JS 方案
import styled from '@emotion/styled'
function App(props) {
const color = "red";
const ErrorMessageRed = styled.div`
color: ${props.color || color};
font-weight: bold;
`;
return (
<div>
<ErrorMessageRed>
hello ErrorMessageRed !!
</ErrorMessageRed>
</div>
);
}
const example = <div className={css`
padding: 0.5rem;
border: 1px solid #ddd;
`}>
...row item...
</div>
classnames
classnames 等价于 clsx,不过 clsx 更加轻量
引入之后,可以实现解析为之后的类名
import classnames from "classnames"
const bottomCardSty=classNames({
[styles.ownBHeight]: true,
[styles.isBChecked]: checked,
[styles.noBChecked]: !checked,
[styles.noBCheckedMq]:!checked&&dataSet.dsCodeType==3,
})
import classnames from 'classnames'
import style from './style.css'
const oneDOM = <div className={style.class1, style.class2}></div>
css-module
create-react-app 中会内置该包
className
中传入的是对象,所以是双括号
function MyComponent(){
return(
<div className={{marginTop:8}}></div>
)
}
css 隔离
- css-module 类似于 vue 中的 scoped
/* style.module.css */
.text{
color:blue
}
/* app.tsx */
import style from './style.module.css'
function FallComponent(){
return(
<div className={style.text}>隔离后的CSS</div>
)
}
// 编译后
.text_fdu25RER{
color:blue
}
styled-jsx
组件友好,的 CSS 内书写方式
scoped and component-friendly CSS
export default () => (
<div>
<p>only this paragraph will get the style :)</p>
{/* you can include <Component />s here that include
other <p>s that don't get unexpected styles! */}
<style jsx>{`
p {
color: red;
}
`}</style>
</div>
)
export default () => (
<div>
<p>only this paragraph will get the style :)</p>
{/* you can include <Component />s here that include
other <p>s that don't get unexpected styles! */}
<style jsx global>{`
body {
background: pink;
}
`}</style>
</div>
)
styled-components
import syled from 'styled-components'
// 创建一个名称为 Title 的 div
const Title = styled.div`
font-size:30px;
background-color:cyan;
`
function App(){
return(
<Title>CSS in JS</Title>
)
}
css-module
import 'index.module.less'
更改全局样式
// 更改 ant-design 的全局样式
:global(.ant-result .ant-result-title) {
color: white;
.ant-result-subtitle {
color: rgba(255, 255, 255, 0.45);
}
}
或者可以
.white{
}
import styles from 'index.module.less'
const Compo = ()=>{
return <div className={styles.white}></div>
}
Tailwind
3d
经典回顾:如何用 React Three Fiber 构建令人惊叹的 3D 场景 - 如果你想用 React 在浏览器中构建 3D 可视化,本文是一篇很好的入门介绍。(这是一年前的文章了,但是现在再看仍然很酷)。
长按识别二维码查看原文
https://varun.ca/modular-webgl/
CSS-in-JS
优点:
- 不污染其它组件,不会影响到其它组件
- 直接在 React 组件内部书写样式,可维护性强
- 可以使用变量控制
缺点:
- 随机类名让 React DevTools 变得难看
- 额外性能(频繁的插入 CSS 样式规则会迫使浏览器做更多的工作)
- 会有更大的概率导致项目报错
推荐配置
参考文章
文章(作者) | 文章链接 |
---|---|
官方文档 | https://reactjs.org |
ConardLi | https://juejin.cn/post/7085542534943883301 |
superZidan | https://juejin.cn/post/7158712727538499598 |