2

When using react-css-modules in a project, I found myself trying to do something that can be simplified to this:

import React from 'react'
import CSSModules from 'react-css-modules'
import ChildComponent from './ChildComponent.jsx'
import styles from './ParentComponent.css'

class ParentComponent extends React.Component {

  render() {
    return (
      <div>
        <p styleName='parentComponent'>This is rendered in ParentComponent</p>
        <ChildComponent styleName='some-name' /> // this style is not applied
      </div>
    )
  }

}

export default CSSModules(ParentComponent, styles)

The CSS class some-name is defined in ParentComponent.css and contains rules that will position ChildComponentwithin ParentComponent.

ChildComponent implementation looks like this:

import React from 'react'
import CSSModules from 'react-css-modules'
import styles from './ChildComponent.css'

class ChildComponent extends React.Component {

  render() {
    return (
      <div> // expected to have this div decorated with 'some-name' class
        <p styleName='childComponent'>This is rendered in ChildComponent</p>
        <button styleName='childComponent'>This is rendered in ChildComponent</button>
      </div>
    )
  }

}

export default CSSModules(ChildComponent, styles)

I was expecting to receive the CSS defined in the some-name class in the first element of what's rendered on ChildComponent (the wrapping ), but this is not happening and 'some-class' is just ignored.

I could workaround this issue by adding an extra wrapping and applying styles to it, but I would like to avoid this if possible:

// in ParentComponent do this instead

render() {
    return (
      <div>
        <p styleName='parentComponent'>This is rendered in ParentComponent</p>
        <div styleName='some-name'>
          <ChildComponent />
        </div>
      </div>
    )
  }

Hopefully I have explained the use case and the issue well enough, so any recommendation on how to do this will be much appreciated.

4

3 回答 3

0

我发现可以通过styles

import styles from './index.css'

class ParentComponent extends React.Component {
  render() {
    return (
      <div>
        <ChildComponent styles={styles}>The title</ChildComponent>
      </div>
    )
  }
}

请注意,父 css 文件中的选择器需要与子 css 文件中的选择器匹配。

在此处查看更详细的示例:https ://github.com/gajus/react-css-modules/issues/220#issuecomment-286473757

于 2017-03-14T11:01:04.577 回答
0

有一个非常简单的解决方案。您需要在该组件中定义styleName,但在该组件内部,您需要在className属性中使用此传递的类道具。因此,您的子组件将如下所示:

class ChildComponent extends React.Component {
  render() {
    return (
      <div className={this.props.className} styleName="some-internal-css-clas">
      </div>
    )
  }
}

并且在输出中,它将class像`class="some-name__uuid some-internal-css-clas__uuid"那样组合css attr。非常容易编写并且非常灵活。希望对你有帮助

于 2018-03-16T22:24:00.763 回答
0

如果您来自 google 并想知道 是什么styleName,请参阅:react-css-modules。它是一个使用 css 模块和作用域 css 的包。

于 2020-09-15T10:04:28.823 回答