React使用Styled-Componets来添加样式

时间:2023-03-10 01:33:54
React使用Styled-Componets来添加样式

React使用Styled-Componets来添加样式


Styled-Comonents是用JS中ES6

语法的方式来管理CSS样式的一个组件,解决了在import CSS文件时样式重复

安装


  1. 项目根目录下打开bash
yarn add styled-components
  1. 新建一个style.js文件来添加样式

注意,这里不是用style.css文件。

使用


style.js

/*
* @Author: YooHoeh
* @Date: 2018-07-17 16:23:09
* @Last Modified by: YooHoeh
* @Last Modified time: 2018-07-18 16:43:05
* @Description:
*/ import styled from "styled-components";
import logoPic from "../../statics/logo.png"; export const HeaderWrapper = styled.div` //导出以一个组件名为HeaderWrapper的样式,
position: reletive;
height: 56px;
// background: red; //支持添加//来添加注释,这行样式将不会执行
border-bottom: 1px solid #f0f0f0f0;
`; export const Logo = styled.a.attrs({
href: "/" //通过attrs()方法为组件添加其他属性
})`
width: 100px;
background: url(${logoPic}); //只能使用import的方式将图片导入,不能填写直接填写本地路径 `;

index.js

/*
* @Author: YooHoeh
* @Date: 2018-07-17 16:18:56
* @Last Modified by: YooHoeh
* @Last Modified time: 2018-07-18 17:48:48
* @Description:
*/ import
'''''';
import {
HeaderWrapper,
Logo
} from "./style"; export default class Header extends Component {
''''
render() {
return (
<HeaderWrapper> //这里用style.js中对应的组件名,渲染的时候会替换成对应的标签类型。
<Logo />
</HeaderWrapper>
);
}
}

进阶用法


子代选择

index.js

    <Item >
<input className='active'/>
<input/>
<input/>
</Item >

style.js

    const Item = styled.div`
font-size:15px;
.active{ //和Sass格式一样,在里面可以直接添加可以表示子代拥有
border:1px solid red;
}
`

多Class名选择

index.js

    <Item className='item active'>1</Item >
<Item className='item'>2</Item >

style.js

    const Item = styled.div`
font-size:15px;
&.active{ //添加&可以表示同时拥有
color:red;
}
`

相关文章