为什么是Styled components

什么是Styled components

使用Styled components,你可以真正地在js文件中写css代码。这意味着你可以使用所有css的功能,比如媒体查询(media queries)、伪类选择器(pseudo-selector), 组合选择器(nesting)等等。和所有同类型的类库一样,通过 js 赋能解决了原生 css 所不具备的能力,比如变量、循环、函数等。

Styled-components使用的是 ES6’s tagged template literals。使用Styled components,组件和样式之间的映射将被移除,这意味着当你在写样式代码的时候,你其实正在创建一个拥有这部分样式的组件。通过styled components, 我们可以创建一个可复用的具有样式的组件,下面将介绍具体的用法。

相对于其他预处理有什么有优点?

(1)诸如 sass&less 等预处理可以解决部分 css 的局限性,但还是要学习新的语法,而且需要对其编译,其复杂的 webpack 配置也总是让开发者抵触。
(2)如果有过sass&less的经验,也能很快的切换到styled-components,因为大部分语法都类似,比如嵌套,& 继承等, styled-componens 很好的解决了学习成本与开发环境问题,很适合 React 技术栈 && React Native 的项目开发。

准备工作

首先,我们需要安装Styled components,在项目根目录下,运行:
$ npm install --save styled-components

如何使用

我们使用 Create-react-app 创建了一个项目
在 src 目录下新建一个 style.js
styled.js

import styled from 'styled-components';
// 使用styled创建一个div
export const TodoComponent = styled.div`
    background-color: #44014C;
    width: 300px;
    min-height: 200px;
    margin: 30px auto;
    box-sizing: border-box;
`;

App.js

import React, { Component } from 'react'
// 引入我们在styled.js抛出的TodoComponent这个样式组件
import { TodoComponent } from './styled'
export default class App extends Component {
  render() {
    return (
      <div>
        <TodoComponent>
          我是被派来测试的
        </TodoComponent>
      </div>
    )
  }
}

在上面的代码中,<TodoComponent>便会使用我们创建的对应的styled component,这个标签的用法跟其他一般的HTML元素基本一样,唯一不同的是它已经具有自己的样式,就是我们在前面的代码中定义的这部分样式。对于其他元素,我们也可以为它们编写样式其他的样式。

自己塑造组件

// 传递className 在react中要使用 style
const Link = ({className , children}) => (
    <a className={className}>
        {children}
    </a>
)
const StyledLink = styled(Link)`
    color: palevioletred;
`
render(
    <div>
        <Link>普通组件</Link>
        <StyledLink>有颜色吗?</StyledLink>
    </div>
);

当然这仅仅是讲了一些入门的知识,想要熟练使用styled components 还需要在实践中探索。

Last modification:October 22nd, 2019 at 09:58 pm
如果觉得我的文章对你有用,请随意赞赏