vue子组件使用父组件样式

tech2022-08-26  130

vue子组件使用父组件样式

Writing future-proof CSS is hard. Conflicting classnames, specificity issues, and so on, come up when you have to write and maintain thousands of lines of CSS. To get rid of the aforementioned issues, Styled Components was created.

编写适用于未来CSS很难。 当您必须编写和维护数千行CSS时,就会出现类名冲突,特殊性问题等等。 为了摆脱上述问题,创建了样式化组件 。

Styled Components makes it easy to write your CSS in JS and makes sure there are no conflicting classnames or specificity issues with multiple other benefits. This makes writing CSS a joy.

样式化的组件使您可以轻松地用JS编写CSS,并确保不存在冲突的类名或特殊性问题,同时具有其他诸多好处。 这使编写CSS成为一种乐趣。

In this tutorial, we’ll explore what CSS in JS is, the pros and cons of styled-components, and finally, we’ll redesign Unsplash using Styled Components. After completing this tutorial, you should be able to quickly get up and running with Styled Components.

在本教程中,我们将探讨JS中CSS是什么, styled-components优缺点,最后,我们将使用样式化组件重新设计Unsplash。 完成本教程后,您应该能够快速启动并使用样式化组件。

Note: Styled Components was specifically built with React in mind, so you have to be using React to use Styled Components.

注意:样式化组件是专门为考虑到React而构建的,因此您必须使用React才能使用样式化组件。

先决条件 (Prerequisites)

For this tutorial, you need a basic knowledge of React.

对于本教程,您需要具备React的基础知识。

Throughout the course of this tutorial we’ll be using yarn. If you don’t have yarn already installed, then install it from here.

在本教程的整个过程中,我们将使用yarn 。 如果尚未安装yarn ,请从此处安装。

To make sure we’re on the same page, these are the versions used in this tutorial:

为了确保我们在同一页面上,这些是本教程中使用的版本:

Node 12.6.0

节点12.6.0 npx 6.4.1

npx 6.4.1 yarn 1.17.3

纱1.17.3

CSS的演变 (Evolution of CSS)

Before CSS-in-JS was created, the most common way to style web apps was to write CSS in a separate file and link it from the HTML.

在创建CSS-in-JS之前,最常见的样式化Web应用程序的方法是在单独的文件中编写CSS并将其与HTML链接。

But this caused trouble in big teams. Everyone has their own way of writing CSS. This caused specificity issues and led to everyone using !important.

但这给大团队带来麻烦。 每个人都有自己CSS编写方式。 这引起了特异性问题,并导致每个人都使用!important 。

Then came Sass. Sass is an extension of CSS that allows us to use things like variables, nested rules, inline imports and more. It also helps to keep things organized and allows us to create stylesheets faster.

然后是萨斯。 Sass是CSS的扩展,允许我们使用变量,嵌套规则,内联导入等功能。 它还有助于使事情井井有条,并允许我们更快地创建样式表。

Even though Sass might be thought of as an improvement over CSS, it arguably causes more harm than good without certain systems put in place.

尽管Sass可能被认为是对CSS的改进,但是如果没有安装某些系统,它可能带来的弊大于利。

Later, BEM came in. BEM is a methodology that lets us reduce specificity issues by making us write unique classnames. BEM does solve the specificity problem, but it makes the HTML more verbose. Classnames can become unnecessarily long, and it’s hard to come up with unique classnames when you have a huge web app.

后来,BEM出现了。BEM是一种方法,使我们可以通过编写唯一的类名来减少特异性问题。 BEM确实解决了特异性问题,但使HTML更加冗长。 类名可能会变得不必要的长,并且当您拥有庞大的Web应用程序时,很难提出唯一的类名。

After that, CSS Modules were born. CSS Modules solved what neither Sass nor BEM could — the problem of unique classnames — by tooling rather than relying on the name given by a developer, which in turn solved specificity issues. CSS Modules gained a huge popularity in the React ecosystem, paving the way for projects like glamor.

之后,CSS模块诞生了。 CSS模块通过工具而不是依靠开发人员提供的名称来解决Sass和BEM都无法解决的问题(唯一类名),这又解决了特定性问题。 CSS模块在React生态系统中获得了极大的普及,为诸如glamor之类的项目铺平了道路。

The only problem with all these new solutions was that developers were made to learn new syntaxes. What if we could write CSS exactly how we write it in a .css file but in JS? And thus styled-components came into existence.

所有这些新解决方案的唯一问题是使开发人员不得不学习新的语法。 如果我们可以完全像在.css文件中但在JS中那样编写CSS,该怎么办? 因此, styled-components应运而生。

Styled Components uses Template Literals, an ES6 feature. Template literals are string literals allowing embedded expressions. They allow for multi-line strings and string interpolation features with them.

样式化组件使用Template Literals (ES6功能)。 模板文字是允许嵌入表达式的字符串文字。 它们允许使用多行字符串和字符串内插功能。

The main selling point of Styled Components is that it allows us to write exact CSS in JS.

Styled Components的主要卖点是它使我们可以用JS编写确切CSS。

Styled Components has a lot of benefits. Some of the pros and cons of Styled Components are listed below.

样式化组件有很多好处。 下面列出了样式化组件的一些优缺点。

优点 (Pros)

There are lots of advantages to using Styled Components.

使用样式化组件有很多优点。

Injecting Critical CSS into the DOM

将关键CSS注入DOM

Styled Components only injects critical CSS on the page. This means users only download CSS needed for that particular page and nothing else. This loads the web page faster.

样式化组件仅在页面上注入关键CSS。 这意味着用户仅下载该特定页面所需CSS,而无需下载其他任何内容。 这样可以更快地加载网页。

Smaller CSS bundle per page

每页较小CSS包

As it only injects styles that are used in the components on the page, bundle size is considerably smaller. You only load the CSS you need, instead of excessive stylesheets, normalizers, responsiveness, etc.

由于它仅注入页面上组件中使用的样式,因此包大小要小得多。 您只加载所需CSS,而不加载过多的样式表,规范化器,响应性等。

Automatic Vendor Prefixing

自动供应商前缀

Styled Components allows you to write your CSS and it automatically vendor prefixes according to the latest standard.

样式化组件允许您编写CSS,并根据最新标准自动为其提供厂商前缀。

Remove unused CSS

删除未使用CSS

With Styled Components, it’s easier to remove unused CSS or dead code, as the styles are colocated with the component. This also impacts on reducing bundle size.

使用样式化组件,可以将未使用CSS或无效代码删除,因为样式与组件位于同一位置。 这也影响减小束的尺寸。

Theming is easy

主题很容易

Styled Components makes it really easy to theme a React applications. You can even have multiple themes in your applications and yet easily maintain them.

样式化的组件使主题React应用程序变得非常容易。 您甚至可以在应用程序中包含多个主题,并且可以轻松维护它们。

Reduces the number of HTTP requests

减少HTTP请求的数量

Since there are no CSS files for resets, normalizers, and responsiveness, the number of HTTP requests are considerably reduced.

由于没有用于重置,规范化和响应CSS文件,因此大大减少了HTTP请求的数量。

Unique Classnames

唯一的类名

Styled Components generates unique classnames every time a build step takes place. This allows avoiding naming collisions or specificity issues. No more having global conflicts and being forced to resolve them with !important tags.

每次进行构建步骤时,样式化组件都会生成唯一的类名。 这样可以避免命名冲突或特异性问题。 不再有全局冲突,而不必使用!important标签解决它们。

Maintenance is easy

维护容易

Styled Components allows you to colocate styles with the component. This allows for painless maintenance. You know exactly which style is affecting your component, unlike in a big CSS file.

带样式的组件使您可以将样式与组件并置。 这样可以轻松进行维护。 与大型CSS文件不同,您确切地知道哪种样式会影响您的组件。

缺点 (Cons)

Of course, nothing’s perfect. Let’s look at some downsides associated with Styled Components.

当然,没有什么是完美的。 让我们看一下与样式化组件相关的一些缺点。

Unable to Cache Stylesheets

无法缓存样式表

Generally, a web browser caches .css files when a user visits a website for the next visit, so it doesn’t have to download the same .css file again. But with styled-components, the styles are loaded in the DOM using the <style> tag. Thus, they can’t be cached and every time user has to request styles when they visit your website.

通常,当用户访问网站进行下一次访问时,Web浏览器会缓存.css文件,因此不必再次下载相同的.css文件。 但是,使用styled-components ,使用<style>标签将样式加载到DOM中。 因此,它们不能被缓存,并且用户每次访问您的网站时都必须请求样式。

React specific

具体React

Styled Components was made with React in mind. Thus, it’s React specific. If you use any other framework, then you can’t use Styled Components.

样式化组件是在考虑React的情况下制作的。 因此,它是特定于React的。 如果使用任何其他框架,则不能使用样式化组件。

However, there’s an alternative very similar to styled-components known as emotion which is framework agnostic.

但是,还有一种与styled-components非常相似的替代方法, styled-components 情感 ,它与框架无关。

实用 (Getting Practical)

Now that we know the pros and cons of Styled Components, let’s start using it.

现在,我们知道样式化组件的优缺点,让我们开始使用它。

Go ahead and scaffold a new React project using create-react-app. To scaffold it, we’ll be using npx, which lets you download and run a package temporarily without polluting the global namespace.

继续并使用create-react-app搭建一个新的React项目。 为了搭建它,我们将使用npx ,它使您可以临时下载并运行程序包,而不会污染全局名称空间。

Type the following in the terminal:

在终端中输入以下内容:

$ npx create-react-app unsplash-styled-components

Then go inside the unsplash-styled-components directory and install the following packages needed for the purpose of this tutorial, namely styled-components and react-medium-image-zoom:

然后进入unsplash-styled-components目录,并安装本教程所需的以下软件包,即styled-components和react-medium-image-zoom :

$ cd unsplash-styled-components $ yarn add styled-components react-medium-image-zoom

The styled-components package allows us to write actual CSS in JS while the react-medium-image-zoom package allows us to zoom in on an image Medium-style.

styled-components包允许我们用JS编写实际CSS,而react-medium-image-zoom包则允许我们放大图像Medium风格 。

Now, once the installation is complete, delete unneeded files like App.css, App.test.js, index.css and logo.svg from the src/ directory.

现在,安装完成后,从src/目录中删除不需要的文件,例如App.css , App.test.js , index.css和logo.svg 。

Go ahead and remove import './index.css'; from index.js, as it’s no longer needed.

继续并删除import './index.css'; 来自index.js ,因为它不再需要。

Replace the contents of App.js with the following:

将App.js的内容替换为以下内容:

import React from 'react' const App = () => <h1>Hello React</h1> export default App

Try running the development server now by typing yarn start in the terminal.

现在,通过在终端中键入yarn start来尝试运行开发服务器。

You should see Hello React printed on the screen like this:

您应该在屏幕上看到Hello React打印:

Styled Components uses tagged template literals to style your component.

样式化组件使用标记的模板文字来对组件进行样式设置。

Let’s suppose you want to style the h1 as white text on a pink background by using Styled Components. Here’s how you would do it:

假设您想通过使用样式化组件将h1样式化为粉红色背景上的白色文本。 这是您的处理方式:

import React from 'react' import styled from 'styled-components' const Header = styled.h1` background-color: pink; color: white; ` const App = () => <Header>Hello React</Header> export default App

It should now look like this:

现在看起来应该像这样:

We just created our first Styled Component Header. The Header component is assigned to styled.h1. The default export styled coming from styled-components has basic HTML primitives like div, span, h1, h2, etc.

我们刚刚创建了第一个样式化组件Header 。 Header组件被分配给styled.h1 。 来自styled-components的默认导出styled具有基本HTML原语,例如div , span , h1 , h2等。

Inside of styled.h1 we write the actual CSS. Notice how we’re writing CSS rather than making style objects.

在styled.h1内部,我们编写了实际CSS。 请注意,我们是如何编写CSS而不是制作样式对象。

Furthermore, the Header component gets replaced in the browser with an h1 tag and a unique classname. A style tag gets inserted into the DOM with the same unique classname. This is the basics of how Styled Components actually work.

此外, Header组件在浏览器中被替换为h1标签和唯一的类名。 使用相同的唯一类名将style标签插入DOM。 这是样式化组件实际工作方式的基础。

Our styles are in the same file as our component. This means our component is co-located with styles. Thus, it’s easier to remove styles associated with a particular component, thereby eliminating dead code.

我们的样式与组件位于同一文件中。 这意味着我们的组件与样式在同一位置。 因此,更容易删除与特定组件关联的样式,从而消除无效代码。

Traditionally in CSS, it’s hard to reason about, as we have to find a particular element’s classname or id or specific selector, then remove them one by one. It’s easy in a small project, but it gets hard as the project complexity increases. With Styled Components, no matter the complexity of the project, it’s easier to add, edit and remove styles, as they’re colocated with the component.

传统上,在CSS中很难推理,因为我们必须找到特定元素的classname或id或特定selector ,然后将它们一一删除。 在一个小项目中这很容易,但是随着项目复杂性的增加而变得困难。 使用样式化组件,无论项目的复杂程度如何,将样式与组件共置在一起时,添加,编辑和删除样式都更加容易。

样式化组件中的主题 (Theming in Styled Components)

Let’s add theming to our project.

让我们将主题添加到我们的项目中。

Create a utils/ folder in the src/ directory. Then create a themes.js file in the utils/ folder. Paste the following in themes.js:

在src/目录中创建utils/文件夹。 然后在utils/文件夹中创建一个themes.js文件。 将以下内容粘贴到themes.js :

export const themes = { common: { fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif", }, light: { type: 'light', bgColor: 'white', color: '#3E4C59', searchBgColor: '#E4E7EB', boxShadow: '0.8rem 0.8rem 1.5rem gray', categoryColor: '#999', categoryHoverColor: '#333', }, dark: { type: 'dark', bgColor: '#1F2933', color: '#E4E7EB', searchBgColor: '#E4E7EB', boxShadow: '0.4rem 0.4rem 1.5rem #111111', categoryColor: '#CBD2D9', categoryHoverColor: '#9AA5B1', }, }

The themes.js file contains an object named themes with three properties: common, light and dark.

themes.js文件包含一个名为themes的对象,该对象具有三个属性: common , light和dark 。

The common property contains common styles across themes, the light property contains styles for the light theme, and the dark property contains styles for the dark theme.

common属性包含跨主题的通用样式, light属性包含浅色主题的样式, dark属性包含深色主题的样式。

Now change App.js as follows:

现在,如下更改App.js :

import React, { useState } from 'react' import styled, { ThemeProvider } from 'styled-components' import { themes } from './utils/themes' const lightTheme = () => ({ ...themes['common'], ...themes['light'], }) const darkTheme = () => ({ ...themes['common'], ...themes['dark'], }) const Header = styled.h1` background-color: pink; color: white; ` const App = () => { const [theme, setTheme] = useState(lightTheme()) const setDarkTheme = () => setTheme(darkTheme()) const setLightTheme = () => setTheme(lightTheme()) return ( <ThemeProvider theme={theme}> <> <Header>Hello React</Header> <button onClick={setLightTheme}>Make it light</button> <button onClick={setDarkTheme}>Make it dark</button> </> </ThemeProvider> ) } export default App

Firstly, we’ve imported the useState hook from react, ThemeProvider from styled-components and themes from ./utils/themes.

首先,我们从react导入useState挂钩,从./utils/themes styled-components导入ThemeProvider ,从./utils/themes themes 。

Then we’ve created two arrow functions, lightTheme and darkTheme.

然后,我们已经创建了两个箭头的功能, lightTheme和darkTheme 。

The lightTheme function returns an object combining the common and light properties from the imported themes variable.

lightTheme函数返回一个对象,该对象结合了导入的themes变量的common和light属性。

So basically, the lightTheme function after evaluation is this:

所以基本上,评估后的lightTheme函数是这样的:

const lightTheme = () => ({ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif", type: 'light', bgColor: 'white', color: '#3E4C59', searchBgColor: '#E4E7EB', boxShadow: '0.8rem 0.8rem 1.5rem gray', categoryColor: '#999', categoryHoverColor: '#333', })

The darkTheme function returns an object combining the common and dark properties from the imported themes variable.

所述darkTheme函数返回一个对象相结合的common和dark从导入的属性themes变量。

Thus, the darkTheme function after evaluation looks like this:

因此,评估后的darkTheme函数如下所示:

const darkTheme = () => ({ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif", type: 'dark', bgColor: '#1F2933', color: '#E4E7EB', searchBgColor: '#E4E7EB', boxShadow: '0.4rem 0.4rem 1.5rem #111111', categoryColor: '#CBD2D9', categoryHoverColor: '#9AA5B1', })

Later, in the App component, we use the useState React hook:

稍后,在App组件中,我们使用useState React钩子:

const App = () => { const [theme, setTheme] = useState(lightTheme()) const setDarkTheme = () => setTheme(darkTheme()) const setLightTheme = () => setTheme(lightTheme()) return ( <ThemeProvider theme={theme}> <> <Header>Hello React</Header> <button onClick={setLightTheme}>Make it light</button> <button onClick={setDarkTheme}>Make it dark</button> </> </ThemeProvider> ) }

useState takes in the default state, which we set to lightTheme(). If you set it to darkTheme(), then by default the dark theme will be displayed. useState returns two variables, which we named theme and setTheme. You can name them anything.

useState处于默认状态,我们将其设置为lightTheme() 。 如果将其设置为darkTheme() ,则默认情况下将显示深色主题。 useState返回两个变量,我们将其命名为theme和setTheme 。 您可以为它们命名。

theme contains the current state — that is, lightTheme() — and setTheme is a function used to set a new state.

theme包含当前状态,即lightTheme() ,而setTheme是用于设置新状态的函数。

Then we have the setDarktheme function, which sets a dark them by calling setTheme and passing it the object returned by the function darkTheme(). The setLightTheme function works in a similar way.

然后,我们有了setDarktheme函数,该函数通过调用setTheme并将其传递给函数darkTheme()返回的对象来设置它们的暗度。 setLightTheme函数以类似的方式工作。

Finally, we have two additional buttons to change themes — one to change it to light and other to dark.

最后,我们还有两个其他按钮可以更改主题-一个按钮将其更改为light ,另一个按钮将更改为dark 。

But for this to work, we need to change our Header component using themes. So change it to the following:

但是,要使其正常工作,我们需要使用主题更改Header组件。 因此将其更改为以下内容:

const Header = styled.h1` background-color: ${props => props.theme.bgColor}; color: ${props => props.theme.color}; `

Now the light theme looks like this:

现在,灯光主题如下所示:

If you try clicking on the Dark Theme button, it will show the dark theme as follows:

如果尝试单击“ Dark Theme按钮,它将显示深色主题,如下所示:

Styled Components has a feature which lets you change your component styles dynamically using a prop. The background-color variable uses the prop theme.bgColor, while color uses the prop theme.color.

样式化组件具有一项功能,可让您使用道具动态更改组件样式。 background-color变量使用prop theme.bgColor ,而color使用prop theme.color 。

The theme variable mentioned here comes from ThemeProvider. The prop provided to ThemeProvider should be named theme. Otherwise it won’t work.

这里提到的theme变量来自ThemeProvider 。 提供给ThemeProvider的道具应命名为theme 。 否则它将无法正常工作。

Now try clicking on the buttons to see themes changing.

现在尝试单击按钮以查看主题更改。

The themes change, but it’s confusing which button to click. Let’s add a conditional that shows the light theme button only when the dark theme is shown, and vice versa.

主题发生了变化,但是单击哪个按钮却令人困惑。 让我们添加一个条件,该条件仅在显示深色主题时才显示浅色主题按钮,反之亦然。

Change the buttons in App.js as follows:

如下更改App.js的按钮:

{theme.type === 'dark' && <button onClick={setLightTheme}>Make it light</button>} {theme.type === 'light' && <button onClick={setDarkTheme}>Make it dark</button>}

This conditional makes sure to only show the relevant button depending on the theme selected.

此条件确保仅根据所选主题显示相关按钮。

Only shows light button on dark theme:

仅在dark主题上显示light按钮:

Only shows dark button on light theme:

仅在light主题上显示dark按钮:

Go ahead and download the assets/ folder and paste it into the src/ directory.

继续并下载assets /文件夹并将其粘贴到src/目录中。

This will ensure we have all the images and icons we need in this project.

这将确保我们拥有该项目中所需的所有images和icons 。

Now let’s change the buttons to icons. We’ll make the light button as a sun icon and dark button as a moon icon.

现在,将按钮更改为图标。 我们将亮按钮作为太阳图标,将暗按钮作为月亮图标。

Import the icons into App.js:

将图标导入App.js :

import { ReactComponent as MoonSVG } from './assets/logos/moon.svg' import { ReactComponent as SunSVG } from './assets/logos/sun.svg'

Then style those icons by extending the SVG. The following adds styles to the svg tag:

然后通过扩展SVG为这些图标设置样式。 以下将样式添加到svg标签:

const SunIcon = styled(SunSVG)` width: 2rem; height: 2rem; margin-left: auto; cursor: pointer; ` const MoonIcon = styled(MoonSVG)` width: 2rem; height: 2rem; margin-left: auto; cursor: pointer; `

Notice how we’re duplicating the code above in both SunIcon and MoonIcon. Styled Components supports reusing styles.

注意我们如何在SunIcon和MoonIcon复制上面的代码。 样式化组件支持重用样式。

样式化组件中的可重用CSS (Reusable CSS in Styled Components)

Styled Components lets us reuse styles using a special helper function named css. Go ahead and import it from styled-components as follows:

样式化组件使我们可以使用名为css的特殊辅助函数来重用样式。 继续,并从styled-components中将其导入,如下所示:

import styled, { css, ThemeProvider } from 'styled-components'

Now you can reuse styles using the css prop as follows:

现在,您可以使用css prop重用样式,如下所示:

const ThemeIcon = css` width: 2rem; height: 2rem; margin-left: auto; cursor: pointer; ` const MoonIcon = styled(MoonSVG)` ${ThemeIcon} ` const SunIcon = styled(SunSVG)` ${ThemeIcon} `

Finally, change the buttons to the following:

最后,将按钮更改为以下内容:

{theme.type === 'light' && <MoonIcon onClick={setDarkTheme} />} {theme.type === 'dark' && <SunIcon onClick={setLightTheme} />}

The App.js file should now like this:

App.js文件现在应如下所示:

import React, { useState } from 'react' import styled, { css, ThemeProvider } from 'styled-components' import { ReactComponent as MoonSVG } from './assets/logos/moon.svg' import { ReactComponent as SunSVG } from './assets/logos/sun.svg' import { themes } from './utils/themes' const lightTheme = () => ({ ...themes['common'], ...themes['light'], }) const darkTheme = () => ({ ...themes['common'], ...themes['dark'], }) const ThemeIcon = css` width: 2rem; height: 2rem; margin-left: auto; cursor: pointer; ` const MoonIcon = styled(MoonSVG)` ${ThemeIcon} ` const SunIcon = styled(SunSVG)` ${ThemeIcon} ` const App = () => { const [theme, setTheme] = useState(lightTheme()) const setDarkTheme = () => setTheme(darkTheme()) const setLightTheme = () => setTheme(lightTheme()) return ( <ThemeProvider theme={theme}> <> <Header>Hello React</Header> {theme.type === 'light' && <MoonIcon onClick={setDarkTheme} />} {theme.type === 'dark' && <SunIcon onClick={setLightTheme} />} </> </ThemeProvider> ) } export default App

And the site should now look like the following. It only shows the moon icon on the light theme:

现在该站点应如下所示。 它仅在light主题上显示moon图标:

And it only shows the sun icon on the dark theme:

并且仅在dark主题上显示sun图标:

样式化零部件中的整体样式 (Global Styles in Styled Components)

Now go ahead and create a components/ folder in src/ directory. Create a file named Global.js inside the components/ folder. Paste the following in it:

现在继续在src/目录中创建一个components/文件夹。 在components/文件夹中创建一个名为Global.js的文件。 在其中粘贴以下内容:

import { createGlobalStyle } from 'styled-components' export const GlobalStyle = createGlobalStyle` *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } html, body { height: 100vh; max-width: 100%; font-size: 62.5%; background-color: ${props => props.theme.bgColor}; color: ${props => props.theme.color}; font-family: ${props => props.theme.fontFamily}; } `

We have imported createGlobalStyle from styled-components. This lets us create global styles. And we later export the GlobalStyle variable as a named export. Notice how we’re using themes in our GlobalStyle. To make sure theming works, we need to make GlobalStyle a child of ThemeProvider. Otherwise it won’t work.

我们已经从styled-components导入了createGlobalStyle 。 这使我们可以创建全局样式。 然后,我们稍后将GlobalStyle变量导出为命名导出。 注意我们如何在GlobalStyle使用主题。 为了确保主题能够正常工作,我们需要将GlobalStyle ThemeProvider的子代。 否则它将无法正常工作。

Go ahead and import Global.js in App.js and use it as follows:

继续,将Global.js导入Global.js App.js以下方式使用它:

import { GlobalStyle } from './components/Global' . . . const App = () => { . . . return ( <ThemeProvider theme={theme}> <> <GlobalStyle /> <Header>Hello React</Header> {theme.type === 'light' && <MoonIcon onClick={setDarkTheme} />} {theme.type === 'dark' && <SunIcon onClick={setLightTheme} />} </> </ThemeProvider> ) } . . .

Global styles should be applied to our web app.

全局样式应应用于我们的Web应用程序。

Global styles applied on the light theme:

应用于light主题的全局样式:

Global styles applied on the dark theme:

适用于dark主题的全局样式:

Now that we know the basics, let’s create the navbar for our Unsplash Redesign. Firstly, go ahead and remove the Header styled component from App.js.

现在我们已经了解了基础知识,让我们为Unsplash Redesign创建导航栏。 首先,继续从App.js删除Header样式的组件。

Then go ahead and add the following in the App.js file:

然后继续,在App.js文件中添加以下内容:

import { ReactComponent as SearchSVG } from './assets/logos/search.svg' import { ReactComponent as UnsplashLogoSVG } from './assets/logos/unsplash-logo.svg' . . . const Nav = styled.nav` display: flex; align-items: center; background-color: ${props => props.theme.bgColor}; box-sizing: border-box; height: 8.2rem; padding-left: 2rem; padding-right: 2rem; position: fixed; width: 100%; z-index: 2; ` const UnsplashLogo = styled(UnsplashLogoSVG)` fill: ${props => props.theme.color}; width: 4rem; height: 4rem; backface-visibility: hidden; box-sizing: border-box; overflow: hidden; vertical-align: middle; ` const TitleWrapper = styled.div` display: flex; flex-direction: column; margin-left: 1rem; ` const Title = styled.h1` display: inline-block; font-size: 2rem; font-weight: 700; color: ${props => props.theme.color}; ` const Subtitle = styled.span` font-size: 1.3rem; font-weight: 500; ` const SearchWrapper = styled.div` display: flex; align-items: center; background: ${props => props.theme.searchBgColor}; border-radius: 3rem; border: 0.05rem solid #cbd2d9; margin-left: 7rem; box-shadow: none; :hover { border: 0.12rem solid #cbd2d9; } ` const SearchIcon = styled(SearchSVG)` fill: #9aa5b1; width: 1.6rem; height: 1.6rem; margin-left: 1.2rem; margin-right: 1rem; ` const SearchBar = styled.input` outline: none; border: none; width: 50rem; padding: 1rem 0; color: ${props => props.theme.categoryHoverColor}; background: transparent; font-size: 1.4rem; font-weight: 300; ` const App = () => { .. .. .. return ( <ThemeProvider theme={theme}> <> <GlobalStyle /> <Nav> <UnsplashLogo /> <TitleWrapper> <Title>Unsplash</Title> <Subtitle>Photos for Everyone</Subtitle> </TitleWrapper> <SearchWrapper> <SearchIcon /> <SearchBar placeholder="Search free high-resolution photos" /> </SearchWrapper> {theme.type === 'light' && <MoonIcon onClick={setDarkTheme} />} {theme.type === 'dark' && <SunIcon onClick={setLightTheme} />} </Nav> </> </ThemeProvider> ) } .. .. ..

Notice that the only thing we’ve done differently is to add a :hover pseudo class on the SearchWrapper component. If you’ve come from Sass or SCSS, then Styled Components is pretty similar. You can even add child selectors inside a Styled Component just like Sass.

注意,我们所做的唯一不同的事情是在SearchWrapper组件上添加了:hover伪类。 如果您来自Sass或SCSS,则样式化组件非常相似。 您甚至可以像Sass一样在样式化组件内添加子选择器。

The nav should be properly displayed now.

导航现在应该正确显示。

The navbar on the light theme:

关于light主题的导航栏:

The navbar on the dark theme:

dark主题上的导航栏:

Let’s create a component for listing categories. Create a file categories.js in the utils/ folder and paste the following:

让我们创建一个列出类别的组件。 创建文件categories.js在utils/文件夹并粘贴以下:

export const categories = [ 'Wallpapers', 'Textures & Patterns', 'Nature', 'Current Events', 'Architecture', 'Business & Work', 'Film', 'Animals', 'Travel', 'Fashion', 'Food & Drink', 'Spirituality', 'Experimental', 'People', 'Health', 'Arts & Culture', ]

Also, create a component named CategoriesList.js in the components/ folder.

另外,在components/文件夹中创建一个名为CategoriesList.js的components/ 。

Paste the following code into it:

将以下代码粘贴到其中:

import React from 'react' import styled from 'styled-components' import { categories } from '../utils/categories' const Categories = styled.div` padding-bottom: 2rem; padding-left: 2rem; position: fixed; margin-top: 8.2rem; top: 0; bottom: 0; overflow-y: scroll; width: 23rem; background: ${props => props.theme.bgColor}; z-index: 2; ` const CategoryName = styled.a` background-color: transparent; cursor: pointer; box-sizing: border-box; color: ${props => props.theme.categoryColor}; display: block; font-size: 1.4rem; font-weight: 500; line-height: 1; padding-bottom: 1.7rem; padding-top: 2.1rem; text-decoration: none; white-space: nowrap; :hover { color: ${props => props.theme.categoryHoverColor}; outline: none; } ` const Category = ({ name }) => <CategoryName href="#">{name}</CategoryName> export const CategoriesList = () => ( <Categories> {categories.map((category, i) => ( <Category name={category} key={i} i={i} /> ))} </Categories> )

Now go ahead and import it in App.js and paste it just below the Nav component:

现在,继续将其导入App.js ,并将其粘贴到Nav组件下面:

import { CategoriesList } from './components/CategoriesList' .. .. .. const App = () => { .. .. .. return ( <ThemeProvider theme={theme}> <> <Nav> .. .. .. </Nav> <CategoriesList /> .. .. .. </> </ThemeProvider> ) } .. .. ..

Now a list of categories will be shown in the sidebar.

现在,类别列表将显示在边栏中。

The list of categories on the light theme:

light主题的类别列表:

The list of categories on the dark theme:

dark主题的类别列表:

Let’s create our final component that displays pics. Create a file named pics.js in the utils/ folder. Paste the following into it:

让我们创建显示图片的最终组件。 在utils/文件夹中创建一个名为pics.js的文件。 将以下内容粘贴到其中:

export const pics = [ require('../assets/pics/asset 0.jpeg'), require('../assets/pics/asset 1.jpeg'), require('../assets/pics/asset 2.jpeg'), require('../assets/pics/asset 3.jpeg'), require('../assets/pics/asset 4.jpeg'), require('../assets/pics/asset 5.jpeg'), require('../assets/pics/asset 6.jpeg'), require('../assets/pics/asset 7.jpeg'), require('../assets/pics/asset 8.jpeg'), require('../assets/pics/asset 9.jpeg'), require('../assets/pics/asset 10.jpeg'), require('../assets/pics/asset 11.jpeg'), require('../assets/pics/asset 12.jpeg'), require('../assets/pics/asset 13.jpeg'), require('../assets/pics/asset 14.jpeg'), require('../assets/pics/asset 15.jpeg'), require('../assets/pics/asset 16.jpeg'), require('../assets/pics/asset 17.jpeg'), require('../assets/pics/asset 18.jpeg'), require('../assets/pics/asset 19.jpeg'), require('../assets/pics/asset 20.jpeg'), require('../assets/pics/asset 21.jpeg'), require('../assets/pics/asset 22.jpeg'), require('../assets/pics/asset 23.jpeg'), require('../assets/pics/asset 24.jpeg'), require('../assets/pics/asset 25.jpeg'), require('../assets/pics/asset 26.jpeg'), require('../assets/pics/asset 27.jpeg'), require('../assets/pics/asset 28.jpeg'), require('../assets/pics/asset 29.jpeg'), require('../assets/pics/asset 30.jpeg'), require('../assets/pics/asset 31.jpeg'), require('../assets/pics/asset 32.jpeg'), require('../assets/pics/asset 33.jpeg'), require('../assets/pics/asset 34.jpeg'), require('../assets/pics/asset 35.jpeg'), require('../assets/pics/asset 36.jpeg'), require('../assets/pics/asset 37.jpeg'), require('../assets/pics/asset 38.jpeg'), require('../assets/pics/asset 39.jpeg'), require('../assets/pics/asset 40.jpeg'), require('../assets/pics/asset 41.jpeg'), require('../assets/pics/asset 42.jpeg'), require('../assets/pics/asset 43.jpeg'), require('../assets/pics/asset 44.jpeg'), require('../assets/pics/asset 45.jpeg'), require('../assets/pics/asset 46.jpeg'), require('../assets/pics/asset 47.jpeg'), require('../assets/pics/asset 48.jpeg'), require('../assets/pics/asset 49.jpeg'), require('../assets/pics/asset 50.jpeg'), require('../assets/pics/asset 51.jpeg'), require('../assets/pics/asset 52.jpeg'), require('../assets/pics/asset 53.jpeg'), ]

Also create a Pic.js file in components/ folder and paste the following:

另外,在components/文件夹中创建一个Pic.js文件,并粘贴以下内容:

import React from 'react' import ImageZoom from 'react-medium-image-zoom' import styled from 'styled-components' const ImageWrapper = styled.div` margin: 0.5rem; transition: all 200ms ease; :hover { box-shadow: ${props => props.theme.boxShadow}; transform: scale(1.005); } ` export const Pic = ({ src, i }) => { const alt = `Unsplash Redesign #${i}` const imageProps = { src, alt } return ( <ImageWrapper> <ImageZoom image={imageProps} zoomImage={imageProps} defaultStyles={{ image: { width: '37rem', height: '48rem' }, }} /> </ImageWrapper> ) }

We’re using react-medium-image-zoom, which lets you zoom in on an image like Medium.

我们正在使用react-medium-image-zoom ,它可以放大像Medium这样的图像。

Now go ahead and import Pic.js in App.js and paste it just below the CategoriesList component. Also, add Grid and GridWrapper styled components as follows:

现在继续导入Pic.js在App.js并粘贴刚才下面的CategoriesList组件。 另外,添加Grid和GridWrapper样式的组件,如下所示:

import { Pic } from './components/Pic' import { pics } from './utils/pics' .. .. .. const GridWrapper = styled.div` display: flex; justify-content: center; ` const Grid = styled.div` padding-top: 8.2rem; padding-left: 23rem; display: grid; grid-template-columns: repeat(3, 38rem); margin-bottom: 1.5rem; ` const App = () => { .. .. .. return ( <ThemeProvider theme={theme}> <> .. .. .. <CategoriesList /> <GridWrapper> <Grid> {pics.map((pic, i) => ( <Pic src={pic} key={i} i={i} /> ))} </Grid> </GridWrapper> </> </ThemeProvider> ) } .. .. ..

Now a grid with pics should appear.

现在应显示带有图片的网格。

The Unsplash redesign with the light theme:

以light主题重新设计的Unsplash:

The Unsplash redesign with the dark theme:

以dark主题的Unsplash重新设计:

We just redesigned Unsplash using styled-components. Try zooming in on the image to see it working. You can check the live demo here.

我们只是使用styled-components重新设计了Unsplash。 尝试放大图像以查看其是否有效。 您可以在此处查看现场演示。

结论 (Conclusion)

Styled Components makes it easy to write plain ol’ CSS in your JS. It allows us to colocate styles with our components so that we can add styles, edit them or remove them easily.

通过样式化组件,可以轻松地在JS中编写普通CSS。 它使我们能够将样式与组件并置在一起,以便我们可以添加样式,编辑样式或轻松删除它们。

We learned how to add Global Styles, reuse styles using a css prop and how to theme an application. We’ve only scratched the surface with styled-components; it has a lot more to offer. You can learn more about it on the official website.

我们学习了如何添加全局样式,如何使用css道具重用样式以及如何为应用程序设置主题。 我们只使用styled-components刮擦表面; 它提供了更多的东西。 您可以在官方网站上了解更多信息。

We finally redesigned Unsplash using Styled Components. The complete code is available on GitHub and the demo is available here.

我们终于使用样式化组件重新设计了Unsplash。 完整的代码可在GitHub上获得 ,该演示可在此处获得 。

翻译自: https://www.sitepoint.com/using-styled-components/

vue子组件使用父组件样式

最新回复(0)