简体   繁体   English

React - 使用内联重要样式

[英]React - using inline important styling

I'm using React in a chrome extension and I need to insert elements into the page via the content script.我在 chrome 扩展中使用 React,我需要通过内容脚本将元素插入页面。 The extension may insert these elements into any page in which it's loaded on (kind of like Last Pass would) so I need to override any existing styling that might target general elements.扩展可以将这些元素插入到加载它的任何页面中(有点像 Last Pass 那样),所以我需要覆盖任何可能针对一般元素的现有样式。

For the most part i've managed to get around this via using iframes as css in iframes can't be modified but I need to give styling to the iFrames and one or two parent containers in order for them to display properly.在大多数情况下,我设法通过使用 iframe 来解决这个问题,因为 iframe 中的 css 无法修改,但我需要为 iFrame 和一两个父容器提供样式,以便它们正确显示。

As i've just learnt you unfortunately can't use the !important feature with inline React CSS.正如我刚刚了解到的,不幸的是,您无法将 !important 功能与内联 React CSS 一起使用。 I can maybe understand why this is but for things live Chrome Extensions that use content scripts I need to be able to use important tags...我也许可以理解为什么会这样,但是对于使用内容脚本的实时 Chrome 扩展程序,我需要能够使用重要的标签......

I've been looking for a work around and managed to find this:我一直在寻找解决方法并设法找到了这个:

react-with-important-style反应重要风格

But whenever the component renders it doesn't look very smooth at all so looking for another option.但是每当组件呈现时,它看起来都不是很平滑,因此寻找其他选项。

Can anyone recommend a good workaround?谁能推荐一个好的解决方法?

Thanks谢谢

I can not say it is a good workaround because it uses refs (inline), but it will do the trick.我不能说这是一个好的解决方法,因为它使用 refs(内联),但它可以解决问题。 You can simply insert this below snippet as an inline property as mentioned in this post在此提到的,你可以简单地低于片段插入此为内联财产

ref={(el) => {
      if (el) {
        el.style.setProperty('background-color', color, 'important');
      }
    }
}

Moreover, there is a hack for earlier versions of ReactJS, that zpao posted.此外, zpao发布了针对较早版本的 ReactJS 的 hack。 ie

style = {
  color: 'red',
  backgroundColor: {
    value: 'blue',
    important: 'true'
  }
}

Another approach is this:另一种方法是这样的:

<style>{"\
i{\
float:none !important;\
}\
"}</style>

Use above code in your JSX as shown below:在 JSX 中使用上面的代码,如下所示:

 let activityStats = <table className="table" id="act-stats-user">
        <style>{"\
            i{\
              float:none !important;\
            }\
          "}</style>
        <tbody>
          ...
        </tbody>
        </table>

If nothing works, then the perfect solution to this problem is to create a custom.css file, import it and write your CSS there with !important (if it`s that important)如果没有任何效果,那么这个问题的完美解决方案是创建一个 custom.css 文件,导入它并在那里使用 !important 编写你的 CSS(如果它很重要)


PS: try to avoid using !important all the time, as it is considered to be a bad practice among the developers but occasionally it`s legal I think :). PS:尽量避免使用!important ,因为它被开发人员认为是一种不好的做法,但我认为偶尔它是合法的:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM