React如何实现像Vue一样将css和js写在同一文件
作者:田本初
这篇文章主要介绍了React如何实现像Vue一样将css和js写在同一文件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
如果想在React中想要像Vue一样把css和js写到一个文件中,可以使用CSS-in-JS。
使用CSS-in-JS
下载
npm i styled-components
使用
就像写scss一样,不过需要声明元素的类型
基本语法及展示如下:
import styled from "styled-components"
export default () => {
const Father = styled.div`
width: 200px;
height: 200px;
background: pink;
span {
font-size: 20px;
}
&: hover {
background: skyblue;
}
`
const Son = styled.span`
color: #f8e;
`
return (
<>
<Father>
<Son>我是Son</Son>
</Father>
</>
)
}
也可以通过styled()选择要继承的样式,并且可以拿到状态。
import { useState } from "react"
import styled from "styled-components"
export default () => {
const Father = styled.div`
width: 200px;
height: 200px;
background: pink;
span {
font-size: 20px;
}
&: hover {
background: skyblue;
}
`
const Son = styled.span`
color: #f8e;
`
const Footer = styled(Father)`
display: ${({ isShow }) => (isShow ? "block" : "none")};
padding: 20px;
border: 1px solid #333;
border-radius: 30px;
`
const [show, setShow] = useState(false)
return (
<>
<Father>
<Son>我是Son</Son>
</Father>
<button onClick={() => setShow(!show)}>点我控制Footer的显示/隐藏</button>
<Footer isShow={show}>我是Footer</Footer>
</>
)
}

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
