styled-components 十分钟入门

392 阅读2分钟

介绍:

styled-components是一个针对react 的 css in js 类库(官方文档)

优点:

 1、styled-components 样式化组件,主要作用是它可以编写实际的CSS代码来设计组件样式,也不需要组件和样式之间的映射,即创建后就是一个正常的React 组件,并且可以附加样式给当前组件。 优化react组件

2、在一个组件内会将结构、样式和逻辑写在一起,虽然这违背了关注点分离的原则,但是这有利于组件间的隔离。为了顺应组件化的潮流

3、使用styled-components不需要再使用className属性来控制样式,而是将样式写成更具语义化的组件的形式

4、使用style-components会随机生成一个class名称,这样不会污染到全局变量

基本使用:

    1、安装 npm install -save styled-components  ||  yarn add styled-components

    2、引入 import styled from "styled-components"

    3、使用:

 import styled from 'styled-components' function App() {  const Title = styled.h1`    font-size: 1.5em;    text-align: center;    color: yellow;  `   return (    <div className="App">      <Title>        Hello World!        </Title>    </div>  );}export default App

相关特性:

一、Adapting based on props - 通过props从父组件获取信息(传参)

 意思就是在使用自定义得到的组件的时候,如果传入了props,可以在里面获取每个属性的值,他的参数是传进来的props

function App() {  const Title = styled.h1`    font-size: 1.5em;    text-align: center;    color: red;  `   const Button = styled.button`     background: ${props => props.primary ? "red" : "white"};    color: ${props => props.primary ? "white" : "red"};     font-size: 1em;    margin: 1em;    padding: 0.25em 1em;    border: 2px solid red;    border-radius: 3px;  `   return (    <div className="App">      <Title>         <Button>Hello World! </Button>        <Button primary>Hello World! </Button>      </Title>    </div>  );}

二、Extending Styles (继承样式) 

1、使用 styled() 来继承组件的样式

const Button = styled.button`
  display: inline-block;
  color: red; 
`;

const TomatoButton = styled(Button)`
  color: yellow;
  border-color: yellow;
`;

2、可以使用 as 属性来改变组件所使用的标签

const Button = styled.button`
  display: inline-block;
  color: red;
  font-size: 1em; 
  border: 2px solid yellow; 
`;

render(
  <div>
    <Button>Normal Button</Button>
    <Button as="a" href="/">hello world</Button>
  </div>
);

三、Define Styled Components outside of the render method

为了避免每次渲染的时候重复生成组件,将生成组件的代码放到 render 外面

四、Pseudoelements, pseudoselectors, and nesting(伪元素、伪选择器和嵌套)

· 伪元素、伪选择器可以直接写在当前的元素定义的地方,表示该组件的样式

· &符号,指向当前的组件

· 如果不适用&附后,该选择器对子元素起作用

const Thing = styled.button`
  color: blue;

  ::before {
    content: '-----';
  }

  :hover {
    color: red;
  }

  &.something {
    background: red;
  }

  .something {
    border: 1px solid; // 可以在子元素中使用这个类
    display: block;
  }
`

五、Attaching additional props (通过 .attrs 添加属性)

使用 .attrs 来为组件/元素传递属性,它的参数可以是对象/函数。函数需要返回一个值

const Input = styled.input.attrs(props => ({ 
  type: "password", 
}))`
  color: red;
  font-size: 1em; 
`;

render(
  <div>
    <Input placeholder="我是一个被设置成密码输入框的input组件" />  
  </div>
)

六、Animations(动画)

const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
`;
 
const Rotate = styled.div`
  display: inline-block;
  animation: ${rotate} 2s linear infinite;
  padding: 2rem 1rem;
  font-size: 1.2rem;
`;

render(
  <Rotate>我是动画</Rotate>
);