本文共 2312 字,大约阅读时间需要 7 分钟。
js如何覆盖组件css样式
How do we style React components in Next.js?
我们如何在Next.js中设置React组件的样式?
We have a lot of freedom, because we can use whatever library we prefer.
我们有很多自由,因为我们可以使用我们喜欢的任何库。
But Next.js comes with built-in, because that’s a library built by the same people working on Next.js.
但是Next.js内置了 ,因为那是由从事Next.js的同一个人构建的库。
And it’s a pretty cool library that provides us scoped CSS, which is great for maintainability because the CSS is only affecting the component it’s applied to.
它是一个非常酷的库,为我们提供了范围内CSS,这对于可维护性非常有用,因为CSS仅会影响所应用的组件。
I think this is a great approach at writing CSS, without the need to apply additional libraries or preprocessors that add complexity.
我认为这是编写CSS的好方法,无需应用其他会增加复杂性的库或预处理器。
To add CSS to a React component in Next.js we insert it inside a snippet in the JSX, which start with
要将CSS添加到Next.js中的React组件中,我们将其插入JSX的一个片段中,该片段以
and ends with
并以
`}
Inside this weird blocks we write plain CSS, as we’d do in a .css
file:
在这个怪异的代码块中,我们编写了纯CSS,就像在.css
文件中所做的那样:
You write it inside the JSX, like this:
您可以在JSX内编写它,如下所示:
const Index = () => ()export default IndexHome page
Inside the block we can use interpolation to dynamically change the values. For example here we assume a size
prop is being passed by the parent component, and we use it in the styled-jsx
block:
在块内部,我们可以使用插值来动态更改值。 例如,在此我们假设父组件正在传递一个size
道具,并在styled-jsx
块中使用它:
const Index = props => ()Home page
If you want to apply some CSS globally, not scoped to a component, you add the global
keyword to the style
tag:
如果要全局应用某些CSS,而不是将其应用于组件,则将global
关键字添加到style
标签:
If you want to import an external CSS file in a Next.js component, you have to first install @zeit/next-css
:
如果要在Next.js组件中导入外部CSS文件,则必须首先安装@zeit/next-css
:
npm install @zeit/next-css
and then create a configuration file in the root of the project, called next.config.js
, with this content:
然后在项目的根目录中创建一个配置文件,名为next.config.js
,其内容如下:
const withCSS = require('@zeit/next-css')module.exports = withCSS()
After restarting the Next app, you can now import CSS like you normally do with JavaScript libraries or components:
重新启动Next应用程序后,您现在可以像通常使用JavaScript库或组件一样导入CSS:
import '../style.css'
You can also import a SASS file directly, using the library instead.
您也可以直接使用库导入SASS文件。
翻译自:
js如何覆盖组件css样式
转载地址:http://ctqgb.baihongyu.com/