我的组件没有读取导入的 Slick CSS [英] My component is not reading imported Slick CSS
问题描述
我正在像这样将 Sick carousel 的 CSS 导入到我的根组件中:
I'm importing Sick carousel's CSS to my root component like this:
import React from 'react'
import PropTypes from 'prop-types'
import { ThemeProvider } from 'styled-components'
import { AppContext } from 'services/AppContext'
import Layout from 'components/blocks/Layout'
import { GlobalStyle, AppContainer } from 'shared/styles'
import theme from 'theme'
import 'slick-carousel/slick/slick.css'
import 'slick-carousel/slick/slick-theme.css'
function App({ Component, pageProps }) {
return (
<AppContext.Provider value={{ foo: 'bar' }}>
<ThemeProvider theme={theme}>
<AppContainer>
<GlobalStyle />
<Layout>
<Component {...pageProps} />
</Layout>
</AppContainer>
</ThemeProvider>
</AppContext.Provider>
)
}
App.propTypes = {
Component: PropTypes.elementType.isRequired,
pageProps: PropTypes.object.isRequired,
}
export default App
问题是样式没有应用于我的轮播.
The problem is that the styles are not being applied to my carousel.
我试图在需要它的组件中导入 CSS,但是 next.js 给我的错误是我必须在根组件中导入它或使其成为组件级 CSS,我不知道怎么办.
I have tried to import the CSS in the component which needs it, but next.js is giving me the error that either I have to import it in the root component or make it component level CSS, which I don't know how to do.
请问有什么建议吗?
推荐答案
我在使用 react-slick 时也遇到了这个问题,它需要很少的 CSS 来自 slick-carousel 的滑块、导航箭头...
I also faced with this issue while using react-slick, it require few CSS from slick-carousel for the slider, navigation arrows...
目前,我有两种解决方案:
Currently, I have two solutions:
- 解决方案 1:将 CSS 导入移至根目录 (
pages/_app.js
)
- Solution 1: Move the CSS import into root (
pages/_app.js
)
// _app.css
...
import 'slick-carousel/slick/slick.css'
import 'slick-carousel/slick/slick-theme.css'
...
// page/_app.js
...
import "./_app.css"
...
评论:它使 react-slick 工作,但 slick-carousel 的 CSS 加载到所有页面上.不太好!
Comment: It makes react-slick working but the slick-carousel's CSS is loaded on all pages. Not so good!
- 解决方案 2(首选):使用
link
标记并将这些 CSS 嵌入您页面的
- Solution 2 (Preferred): Use the
link
tag and embed these CSS in your page's<head>
// I downloaded the CSS, minified them and put in the public folder
/public/static/css/slick.css
/public/static/css/slick-theme.css
// page/example.js
import Head from "next/head"
...
<Head>
// Embed local CSS
<link rel="stylesheet" type="text/css" href="/static/css/slick.css" />
<link rel="stylesheet" type="text/css" href="/static/css/slick-theme.css" />
// Or we can change the href to CDNs too
</Head>
评论:我们只在我们需要的页面中嵌入和加载样式,也许这有助于节省字节.
Comment: We only embed and load styles in pages that we need, maybe it helps saving bytes.
这篇关于我的组件没有读取导入的 Slick CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!