2017-08-14 13 views
1

因此,我正在构建一个基于React的平台,并且该平台已经具有全局CSS,已经以某种方式为所有客户端设置了全局CSS。如何在特定网站的React组件中调用特定的CSS样式表?

在一个公共组名下的子公司的子集想要一个新的粘性广告组件,必须改变CSS一点,所以页脚不会被掩盖。因此通常,我会检查我们的全局变量值是什么,window.client.group,如果它是特定的组,则通过javascript在联属js文件(我们的旧通用平台)中添加css或css样式表。

所需要的新的CSS是:

@media (max-width:767px){ 
    #ad201 {width:100%;position:fixed;bottom:0;left:0;z- 
index:99999;margin:0;border:1px solid rgb(232, 232, 232);background- 
color:#fff;margin: 0 !important;} 
    .Footer .container {padding-bottom:50px;} 
    } 

在阵营虽然,什么是做到这一点的最好和最合适的方法是什么? 正如您所看到的,需要参与媒体查询会很复杂。

我已经开始使用group和matchMedia,但引入CSS的最佳方式是什么?整个样式表? (stickyAd.css?一些其他方式?以及有关如何操作的提示?)

const group = (window.client.group).toLowerCase(); 
console.log(group); 

const mq = window.matchMedia("(max-width: 767px)"); 

if ((mq.matches) && (group === 'premiere')) { 
    // bring in the new css 
} else { 
    // do nothing 
} 

感谢您的建议!

+0

你可以看看这个:https://github.com/styled-components/styled-components或只是谷歌为“javascript动态添加css – Hardy

+0

是否有任何理由,你不能只是在你的CSS中的某个地方申报一个新的类,它将添加所需的规则时,添加到您检测到的对象?媒体查询可以在类声明内声明 – philraj

+0

谢谢@Hardy,将检查它 – nyhunter77

回答

1

这取决于您对ad201Footer有多少控制权。

我假设Footer是您在React中创建的组件。在这种情况下,你可以(你大概能想到一个更好的名字)添加类像premiere-footer-fix到被渲染组件时,你发现你的组:

render() { 
    const group = (window.client.group).toLowerCase(); 

    return (
    <Footer className={group === 'premiere' ? 'premiere-footer-fix' : ''}/> 
) 
} 

,或者如果您导入非常方便classnames包,

import classNames from 'classnames'; 

// ... 

render() { 
    const group = (window.client.group).toLowerCase(); 
    const classes = classNames({ 
    'premiere-footer-fix': group === 'premiere' 
    }); 

    return (
    <Footer className={classes}/> 
) 
} 

那么无论你声明CSS的页脚,你只需要添加类似:

@media (max-width:767px) { 
    .Footer.premiere-footer-fix .container { 
     padding-bottom: 50px; 
    } 
} 

至于你的广告,你必须提供铁道部有关它如何被插入到页面的信息,因为它不清楚你对元素有多少控制。但是我想补充premiere到广告的classList,找到要插入该位CSS的地方:

@media (max-width:767px) { 
    #ad201.premiere { 
    width: 100%; 
    position: fixed; 
    bottom: 0; 
    left: 0; 
    z-index: 99999; 
    margin: 0; 
    border: 1px solid rgb(232, 232, 232); 
    background-color: #fff; 
    margin: 0 !important; 
    } 
} 
+0

花了一段时间回到这里,但感谢您的建议!我最终决定使用类名,并且使它变得简单。我们使用来自JSON的道具来启用和禁用组件中默认设置的功能。我添加了一个类名,如果广告具有粘合支柱和页脚移动,则应该激活,以便设置一个道具。这很好,因为我们可以使用页脚支持来自第三方的其他粘性广告。太棒了! – nyhunter77

+0

很高兴你把所有东西都整理出来。 :-) – philraj