2017-10-12 80 views
1

我使用react.js和我有我的WebPack简单的规则如何编写嵌套样式?

 { 
      test: /\.css$/, 
      exclude: /node_modules/, 
      use: [ 
       {loader: 'style-loader'}, 
       {loader: 'css-loader', options: {modules: true}} 
      ] 
     } 

我做的一切,我处理我的CSS样式与风格和CSS装载机的帮助,所以我可以写模块,一切正常的CSS很好,但我不明白怎么写嵌套样式,例如我有这样

import React from 'react'; 
import ReactDOM from 'react-dom'; 

import ButtonCSS from "./button.css"; 
import HeaderCSS from "./header.css"; 
import ArticleCSS from "./article.css"; 

const Button = ({title}) => { 
    return (
     <div className={ButtonCSS.defaultButtonStyle}> 
      {title} 
     </div> 
    ); 
}; 

const Page =() => { 
    return (
     <div> 
      <header className={HeaderCSS.defaultStyle}> 
       <Button title="Search" /> 
      </header> 
      <article className={ArticleCSS.defaultStyle}> 
       <Button title="Registration" /> 
      </article> 
     </div> 
    ); 
}; 

ReactDOM.render(
    <Page />, 
    document.querySelector('.container') 
); 

这里JSX代码我想要什么我的默认项目按钮将红色搜索,橙登记,但样式按钮和标题在不同的.css文件中,并且它们被编译为随机哈希,如下所示:

<div class="container"> 
    <div data-reactroot=""> 
     <header class="_1drImxMAqFTeL1TQCthA-D"> 
      <div class="_1Itfki2yr_IamWL2zkYKwW">Registration</div> 
     </header> 
     <article> 
      <div class="_1Itfki2yr_IamWL2zkYKwW">Registration</div> 
     </article> 
    </div> 
</div> 

,所以我不能只是单纯的喜欢写东西

header .magic { 
    do something ... 
} 

如果我将开始在我所有的.css文件使用:global,这将是在所有使用模块的地步?

回答

0

您应该使用组合:https://github.com/css-modules/css-modules#composition

这样,你将有两个类扩展一个包含所有常用css的类。

+0

所以要改变按钮的风格,我需要在'button.css'中创建额外的风格,然后从'header.css'编写样式,然后以某种方式使用由'header.css'风格组成的新'button.css'反应组件,并重复所有这一切,每次我想使用我的默认项目按钮的地方? – MyMomSaysIamSpecial