React-组件-CSS-In-JS
- 在 React 中, React 认为结构和逻辑是密不可分的, 所以在 React 中结构代码也是通过 JS 来编写的
- 正是受到 React 这种思想的影响, 所以就有很多人开发了用 JS 来编写 CSS 的库
比较火热的库有:styled-components
/ emotion
- 利用 JS 来编写 CSS, 可以让 CSS 具备样式嵌套、函数定义、逻辑复用、动态修改状态等特性
- 也就是说, 从某种层面上, 提供了比过去 Less/Scss 更为强大的功能
- 所以 CSS-In-JS, 在 React 中也是一种比较推荐的方式
styled-components 的使用
- 安装 styled-components
npm install styled-components --save
- 导入 styled-components
import styled from 'styled-components';
- 利用 styled-components 创建组件并设置样式
styled.div`
xxx:xxx
`
案例
import React from 'react';
import styled from 'styled-components';
const StyleDiv = styled.div`
p{
font-size: 50px;
color: red;
}
a{
font-size: 25px;
color: green;
}
`;
class Home extends React.Component {
render() {
return (
<StyleDiv>
<p>我是home段落</p>
<a href={'https://www.cnblogs.com/BNTang/'}>我是home超链接</a>
</StyleDiv>
)
}
}
export default Home;
注意点
- 默认情况下,在 webstorm 当中编写 styled-components 的代码是没有任何的代码提示的
- 如果想要有代码提示,那么必须给 webstorm 安装一个插件,插件名字为
webstorm-styled-components
- 由于该插件需要FQ,所以博主这里提供下载链接:https://www.aliyundrive.com/s/BBGgHFiH7fd