【问题标题】:Inline style for chrome and firefox in react反应中chrome和firefox的内联样式
【发布时间】:2018-04-25 21:04:44
【问题描述】:

我在 react 中为 div 使用了一些内联样式。所以,我使用了 width: max-content 作为 div。它在 chrome 中运行良好,但在 Firefox 中,我必须使用 -moz-max-content。 那么,有没有办法在 react 中使用内联样式为 chrome 和 firefox 指定样式?

const divStyle = {
    margin: 'auto',
    width: 'max-content',
    fontSize: 24
  }

我不能为 firefox 使用另一个宽度键,这会引发错误。

我的反应版本是 15.6.1

【问题讨论】:

  • 每个元素只能使用一个这样的样式块吗?

标签: css reactjs inline-styles


【解决方案1】:

这(使用内联样式为同一属性添加多个后备值)不受官方支持,并且可能永远不会支持。请参阅 Dan Abramov 的评论(并阅读有关 github 问题的整个讨论以了解一些历史):

https://github.com/facebook/react/issues/6467#issuecomment-354781011

他建议的解决方案:

例如,您可以使用 document.createElement('div') 创建一个 DOM 节点,然后分配 .style.myPrefixedProperty 并通过读取它来查看它是否“粘住”。

【讨论】:

    【解决方案2】:

    如果你要在 reactjs 中做内联样式,那么你最好使用像 Radium 这样的库。它支持自动供应商前缀。

    其他示例是 glamorous cssglamor 这两个库都支持供应商前缀。

    【讨论】:

      【解决方案3】:

      您只需将 [Autoprefixer][1] 用于对象样式

      如果你还在使用 npm,你可以运行npm i --save inline-style-prefixer

      import Prefixer from 'inline-style-prefixer'
      
      const divStyle = {
          margin: 'auto',
          width: 'max-content',
          fontSize: 24
        }
      
      const prefixer = new Prefixer()
      const prefixedStyle = prefixer.prefix(divStyle)
      

      他们还提供 UMD 链接

      <!-- Unminified versions -->
      <script src="https://unpkg.com/inline-style-prefixer@3.0.1/dist/inline-style-prefixer.js"></script>
      <script src="https://unpkg.com/inline-style-prefixer@3.0.1/dist/inline-style-prefix-all.js"></script>
      <!-- Minified versions -->
      <script src="https://unpkg.com/inline-style-prefixer@3.0.1/dist/inline-style-prefixer.min.js"></script>
      <script src="https://unpkg.com/inline-style-prefixer@3.0.1/dist/inline-style-prefix-all.min.js"></script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-12
        • 2020-07-15
        • 2020-09-05
        • 2018-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-14
        相关资源
        最近更新 更多