盖茨比乔布斯_在盖茨比中使用样式化组件

盖茨比乔布斯

When creating a new Gatsby.js project, there are several available options for styling. We could write our own CSS/SCSS stylesheets, install frameworks like Bootstrap, and/or use various CSS-in-JS solutions. styled-components is one of the most popular CSS-in-JSS solutions, and for good reason. It’s powerful, easy to learn, and it works flawlessly with Gatsby. Let’s explore how to add it into your project!

创建新的Gatsby.js项目时,有几种可用的样式选项。 我们可以编写自己CSS / SCSS样式表,安装Bootstrap之类的框架,和/或使用各种CSS-in-JS解决方案样式组件是最流行CSS-in-JSS解决方案之一,这有充分的理由。 它功能强大,易于学习,并且可以与Gatsby完美协作。 让我们探讨如何将其添加到您的项目中!

This post assumes that you already have a working Gatsby.js project that is ready to edit. (If you need help with that, please follow the steps in Your First Steps with Gatsby v2 and then return here afterwards.)

这篇文章假定您已经有一个可以编辑的Gatsby.js项目。 (如果您需要帮助,请按照《 使用Gatsby v2的第一步》中的步骤进行操作 ,然后再返回此处。)

安装 (Installation)

Installing styled-components into our Gatsby project is an extremely easy two-step process.

styled-components安装到我们的Gatsby项目中是非常容易的两步过程。

1.安装所需的依赖项: (1. Install the required dependencies:)

For the first step, we just need to install three (required) dependencies from npm:

第一步,我们只需要从npm安装三个(必需)依赖项:

  • styled-components: The main styled-components framework, which is an extremely elegant and flexible CSS-in-JS solution built for React. It automatically handles SSR, auto-prefixing, and MUCH more. (See their fantastic documentation here: styled-components docs)

    styled-components :主要的styled-components框架,这是一个为React构建的极其优雅且灵活CSS-in-JS解决方案。 它会自动处理SSR,自动前缀和更多内容。 (在此处查看其出色的文档: styled-components docs )

  • gatsby-plugin-styled-components: The official Gatsby.js plugin for styled components.

    gatsby-plugin-styled-components :用于样式化组件的官方Gatsby.js插件。

  • babel-plugin-styled-components: This is a plugin for Babel that provides more legible class names, server-side rendering ability, smaller bundle sizes, and more. (Gatsby depends on this, but we won’t have to make any manual edits to a .babelrc file.)

    babel-plugin-styled-components :这是Babel的插件,提供了更清晰的类名,服务器端渲染功能,更小的捆绑包大小等。 (Gatsby依赖于此,但是我们不必对.babelrc文件进行任何手动编辑。)

Let’s navigate to our project root directory, and run the following from the command prompt:

让我们导航到我们的项目根目录,然后在命令提示符下运行以下命令:

$ yarn add styled-components gatsby-plugin-styled-components babel-plugin-styled-components

Note: It’s ok to install these with npm, if you prefer using that!

注意:如果愿意,可以使用npm安装它们!

2.将插件添加到您的Gatsby配置中: (2. Add the plugin to your Gatsby config:)

For the second/final step, we add the plugin into our Gatsby configuration. In our project’s gatsby-config.js file, let’s add it to the plugins array.

对于第二步/最后一步,我们将插件添加到Gatsby配置中。 在我们项目的gatsby-config.js文件中,让我们将其添加到plugins数组中。

gatsby-config.js
gatsby-config.js
module.exports = {
  ...
  plugins: [
    {
      resolve: `gatsby-plugin-styled-components`,
      options: {
        // Change plugin default options here, e.g.:
        // ssr: false
        // displayName: false, 
        // minify: false
      },
    },
    //... other plugins
  ]
}

There are a few options available for overriding the default settings, such as disabling minification or server-side rendering. A complete list and description of these can be found here in the styled-components docs.

有一些选项可用于覆盖默认设置,例如禁用缩小或服务器端呈现。 这些的完整列表和描述可以在styled-components文档中找到。

If you don’t plan on customizing the plugin options (and I rarely do), a quicker single-line approach also works:

如果您不打算自定义插件选项(我很少这样做),那么更快速的单行方法也可以:

gatsby-config.js
gatsby-config.js
module.exports = {
  ...
  plugins: [
    `gatsby-plugin-styled-components`,
     //... other plugins
  ]
}

That’s all! styled-components is now installed and ready for use in our Gatsby project.

就这样! 现在已安装样式化组件,并准备在我们的Gatsby项目中使用。

用法 (Usage)

This post is not meant to be a detailed lesson in using styled-components, as that would be a lengthy post on its own! However, let’s create a few quick examples to demonstrate usage in our Gatsby project.

这篇文章并不打算成为使用样式化组件的详细课程,因为那将是一篇冗长的文章! 但是,让我们创建一些简单的示例来演示Gatsby项目中的用法。

创建一个新页面 (Create a new page)

To keep things as simple as possible, let’s first create a basic ‘demo’ page at /src/pages/sc-demo.js.

为了使事情尽可能简单,让我们首先在/src/pages/sc-demo.js创建一个基本的“演示”页面。

/src/pages/sc-demo.js
/src/pages/sc-demo.js
import React from 'react';
import { Link, graphql } from 'gatsby';
import Helmet from 'react-helmet';

import Layout from '../components/layout';

class SCDemoPage extends React.Component {
  render() {
    const siteData = this.props.data.site.siteMetadata;
    const siteTitle = siteData.title;
    const siteDescription = siteData.description;

    return (
      <Layout location={this.props.location}>
        <Helmet
          htmlAttributes={{ lang: 'en' }}
          meta={[{ 
            name: 'description', 
            content: siteDescription 
          }]}
          title={siteTitle}
        />

        <section>
          <h2>Styled Components Demo</h2>

          <div>
            <h3>Banana Milkshakes</h3>
            <p>We'll definitely need frozen bananas 
            and some milk.</p>

            <Link to='/'>To Homepage</Link>
          </div>
        </section>
      </Layout>
    )
  }
};

export default SCDemoPage;

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
        description
      }
    }
  }
`;

导入和使用样式化组件 (Import and use styled-components)

We’re just going to add some simple styles to our 'Banana Milkshakes’ div. First, let’s import styled-components at the top of the page, right after the Helmet import line:

我们将为“香蕉奶昔” div添加一些简单的样式。 首先,让我们在Helmet导入行之后Helmet在页面顶部导入styled-components

import React from 'react';
import { Link, graphql } from 'gatsby';
import Helmet from 'react-helmet';

import styled from "styled-components"; // 💅 yay!

Then, just under the Layout import line, let’s create two styled components. For the first one, CustomBox, we will create a component that applies styling to an HTML div element. (Notice the SASS-like nesting.)

然后,在“ Layout导入行下,让我们创建两个样式化的组件。 对于第一个CustomBox ,我们将创建一个将样式应用于HTML div元素的组件。 (请注意类似SASS的嵌套。)

const CustomBox = styled.div`
  border: 1px solid rgb(0, 143, 104);
  padding: 20px;

  h3 {
    color: rgb(109, 182, 91);
    margin: 0 0 10px;
    padding: 0;
  }
`

For the second one, we will apply styles to Gatsby’s Link component. This is to demonstrate that you can style nearly any component, not just HTML elements! (I’ve used it to tweak react-bootstrap components, for example.)

对于第二个,我们将样式应用于Gatsby的Link组件 。 这是为了证明您可以样式化几乎所有组件,而不仅仅是HTML元素! (例如,我用它来调整react-bootstrap组件。)

const StyledLink = styled(Link)`
  color: red;
`

Important: Note the use of [template literal strings](https://www.digitalocean.com/community/tutorials/js-template-literals-es6) in both items above! (Those are backticks, not single quotes.)

重要:请注意,在以上两个项目中都使用了[模板文字字符串]( https://www.digitalocean.com/community/tutorials/js-template-literals-es6 )! (这些是反引号,而不是单引号。)

使用页面内的新组件 (Use the new components inside the page)

Now we can put these to use! First, let’s swap the plain div tag surrounding our Banana Milkshakes info with the new CustomBox tag. Then, replace the Link tag with the StyledLink tag.

现在我们可以使用它们了! 首先,让我们将香蕉奶昔信息周围的普通div标签替换为新的CustomBox标签。 然后,将Link标签替换为StyledLink标签。

And here is the result:

结果如下:

<CustomBox>
  <h3>Banana Milkshakes</h3>
  <p>We'll definitely need frozen bananas 
  and some milk.</p>
  <StyledLink to="/">To Homepage</StyledLink>
</CustomBox>

That’s it! If your Gatsby site is running in development mode, you’ll see the styles update immediately after saving.

而已! 如果您的Gatsby网站正在开发模式下运行,则保存后您会立即看到样式更新。

结论 (Conclusion)

Adding styled-components to your Gatsby.js project is not difficult, and can be a real game-changer. This demo barely scratches the surface, so I encourage you to dig deeper into the styled-components documentation to see all the amazing things it can do!

在您的Gatsby.js项目中添加样式化组件并不困难,并且可以真正改变游戏规则。 该演示几乎不会触及表面,因此我建议您更深入地研究样式化组件文档,以了解它可以做的所有令人惊奇的事情!

翻译自: https://www.digitalocean.com/community/tutorials/gatsbyjs-using-styled-components-in-gatsbyjs

盖茨比乔布斯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值