【问题标题】:Pass in a stylesheet as a prop for a render in a functional component传入样式表作为功能组件中渲染的道具
【发布时间】:2020-02-14 17:01:17
【问题描述】:

如果重要的话,我正在使用 Next.js、React、Styled JSX 和 Postcss。我需要为特定页面设置导入组件的样式。由于样式表是在渲染时为特定组件创建的,我想我可以将组件的自定义样式与页面特定资源一起放入并传递它们。但是我收到以下错误:

Expected a template literal or String literal as the child of the JSX Style tag (eg: <style jsx>{`some css`}</style>), but got MemberExpression

我在两个单独的目录和文件中有两个功能渲染,一个是页面,另一个是组件:

src/pages/mypage/
    index.js
    styles.css
    myComponentStyles.css
src/components/MyComponent
    index.js
    styles.css

请记住,文件/目录引用没有从我的环境镜像,因为这不是问题,这是我的代码:

src/pages/mypage/index.js

import MyComponent from '../../components/MyComponent'
import styles from './styles.css'
import MyComponentStyles from './myComponentSyles'

const MyPage = () => {
  return (
    <div className="my-page-container">
      <style jsx>{styles}</style>
      <MyComponent styles={MyComponentStyles} />
    </div>
  )
}

export default MyPage

src/components/MyComponent/index.js

import styles from './styles.css'

const myComponent = props => {
  return (
    <>
      <style jsx>{styles}</style>
      <style jsx>{props.styles}</style>
      <div className="my-component-main-container">MyComponent</div>
    </>
  )
}

export default MyComponent

我如何允许MyComponent 接收由另一个组件生成的样式表?

【问题讨论】:

  • 你试过了吗:
  • @SteveHolgado 如果您指的是MyComponent,则正常样式导入有效。如果是这样的话,我为了清楚起见编辑了我的问题。但是,如果您说将样式从 scr/pages/mypage/myComponentStyles.css 直接导入到 MyComponent 函数中,那是行不通的。这不会使组件加载传递给它的样式。

标签: javascript css reactjs jsx next.js


【解决方案1】:

虽然这不是问题的直接解决方案,但 Styled JSX 有一个 :global() 伪选择器,它完成了为当前组件范围之外的组件设置样式的最终目标。给定代码的一个工作示例是:

src/pages/mypage/styles.css

.my-page-container :global(.my-component-main-container){
  color: white;
}

这是 Next.js documentation:global() 伪选择器所说的内容:

一次性全局选择器

有时跳过选择器范围很有用。为了得到一个 我们支持的一次性全局选择器 :global(),灵感来自 css-modules。

这对于例如生成全局类非常有用 您可以将其传递给 3rd-party 组件。例如,样式 react-select 支持通过自定义类 选项类名:

import Select from 'react-select'

export default () => (
  <div>
    <Select optionClassName="react-select" />
    <style jsx>{`
      /* "div" will be prefixed, but ".react-select" won't */

      div :global(.react-select) {
        color: red
      }
    `}</style>
  </div> )

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多