【问题标题】:Adding style attributes to a css class dynamically in react app在反应应用程序中动态地将样式属性添加到css类
【发布时间】:2017-05-21 01:34:33
【问题描述】:

我正在使用带有 css-loader 的 webpack 来加载我的 css 样式并将它们添加到 React 组件中。

import styles from '../styles/cell.css';

.cell {
    border-radius: 50%;
    background-color: white;
}

<div className={styles.cell} />

我正在动态计算单元格的高度/宽度。 Here 他们描述了如何为组件动态添加样式,但我更喜欢在没有样式属性的情况下这样做。

我尝试在其中一个父组件中执行此操作,认为它可能会改变 css 类,但这似乎不起作用。

import cell_styles from '../styles/cell.css';
cell_styles.width = this.cellSize + 'px'
cell_styles.height = this.cellSize + 'px'

关于如何最好地做到这一点的任何反馈?

【问题讨论】:

    标签: reactjs css-loader


    【解决方案1】:

    您可以在动态的 CSS 属性(例如,宽度和高度)上尝试 CSS 自定义属性:

    // cell.css
    
    .cell {
      width: var(--width);
      height: var(--height);
    }
    

    然后您可以在父容器中提供 CSS 变量的值(CSS 变量也向下级联):

    <div style={{ '--width': `${something}px`, '--height': `${something}px` }}>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
    </div>
    

    将其视为传递给子级的“CSS 参数/道具”。

    这种方法的一个好处是您可以避免更新和重新渲染子组件。

    【讨论】:

    • 这是一个很棒的选择。特别是对于像:hover 这样的伪类,因为它们无法通过 style 属性访问。要与 typescript 一起使用,必须转换 css 变量,因为它不是 css 属性。 ['--width' as any]: ${ something }+'px'
    【解决方案2】:

    您应该使用 style 属性,这就是它的目的。

    import classLevelStyles from '../styles/cell.css';
    
    const style = {
        width:  this.calcWidth()  + 'px',
        height: this.calcHeight() + 'px',
    };
    
    <div className={classLevelStyles} style={style} />
    

    【讨论】:

    • 很好奇是否还有其他方法。无论如何,这对我有用。只想指出,元素上的属性是“样式”(不是“样式”)。谢谢。
    猜你喜欢
    • 2019-10-31
    • 2020-04-30
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2019-01-29
    • 2018-12-23
    • 2019-12-08
    相关资源
    最近更新 更多