美文网首页Front End
[FE] hello-styled-components

[FE] hello-styled-components

作者: 何幻 | 来源:发表于2017-07-25 14:58 被阅读185次

1. 项目初始化

npm init

2. 安装开发环境依赖

npm install --save-dev \
babel-core \
babel-loader \
babel-preset-es2015 \
babel-preset-react \
webpack

3. 安装模块依赖

npm install --save \
react \
react-dom \
styled-components

4. 新建./.babelrcwebpack.config.js两个文件

(1).babelrc

{
    "presets": [
        "es2015",
        "react"
    ]
}

(2)webpack.config.js

const path = require('path');

module.exports = {
    entry: {
        index: './index.jsx'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        libraryTarget: 'umd'
    },
    module: {
        loaders: [{
            test: /.jsx$/,
            loader: 'babel-loader'
        }]
    }
};

5. 例子

(1)目录结构

+ dist    //自动生成的目录
+ node_modules    //自动生成的目录
.babelrc
index.html
index.jsx
package-lock.json    //自动生成的文件
package.json
webpack.config.js

(2)index.jsx

import React from 'react';
import ReactDOM from 'react-dom';

import styled from 'styled-components';

// 1. 新建一个带样式的组件
const Title = styled.div`
    font-size: 1.5em;
    color: ${props => props.primary ? 'red' : 'black'}
`;

// 2. 给已有组件添加样式
const Link = ({ className, children }) => (
    <a className={className}>
        {children}
    </a>
)
const StyledLink = styled(Link) `
    font-size: 1.5em;
    color: ${props => props.primary ? 'red' : 'black'}
`;

ReactDOM.render(
    <div>
        <Title primary>Title</Title>
        <StyledLink primary>StyledLink</StyledLink>
    </div>,
    document.getElementById('page')
);

注:
(1)styled-components使用了tagged template literals,来处理样式表。

(2)使用styled-components可以直接创建一个带样式的React组件。
还可以为已有组件添加样式,组件中使用className来获取所添加的样式。

(3)样式表模板字符串中,所出现的函数props => ...,会自动使用组件的属性进行调用。所以,以下两种用法的作用效果是相同的,

color: ${props => props.primary ? 'red' : 'black'}
${props => props.primary ? 'color: red' : 'color: black'}

本例中,在创建Title组件时,使用props.primary获取了组件<Title primary>Title</Title>primary属性值。


参考

styled-components.com
ECMAScript 2017 Language Specification: Tagged Templates
MDN: Tagged template literals

相关文章

  • [FE] hello-styled-components

    1. 项目初始化 2. 安装开发环境依赖 3. 安装模块依赖 4. 新建./.babelrc和webpack.co...

  • codis 小结(配置)

    通过codis-fe进行web操作管理:注意在fe上添加的时候需要保证这些进程存在,fe不会自动开启,只是对这些已...

  • 词为我用 - barefaced

    ​词汇释义 barefaced UK /ˈbeə.feɪst/ US /ˈber.feɪst/ TEM8IELTS...

  • Untitled

    fe # fjoe

  • Apache Doris——安装部署之扩容缩容

    1. FE 扩容和缩容 可以通过将 FE 扩容至 3 个以上节点来实现 FE 的高可用。 用户可以通过 mysql...

  • li fe

  • chi fe

    哈哈

  • [FE] tapable

    tapable[https://github.com/webpack/tapable] 是 webpack[htt...

  • Fe-13 HTML5

    Fe-13-1 Fe-13-2 particles.jshttp://www.phaserengine.com/h...

  • 感情

    刚才和姐妹聊天,聊到关于fe类型的人格。 fe是荣格八维其中之一,也是MBTI的基础,作为fi和ti双强的我,fe...

网友评论

    本文标题:[FE] hello-styled-components

    本文链接:https://www.haomeiwen.com/subject/ayvwkxtx.html