Adding style attributes to a css class dynamically in react app

♀尐吖头ヾ 提交于 2019-12-05 06:09:43

问题


I'm using webpack with css-loader to load my css styles and add them to React components.

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

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

<div className={styles.cell} />

I'm calculating the height/width for the cell dynamically. Here they describe how to add styles to components dynamically, but i'd prefer doing this without the style attribute.

I tried doing this in one of the parent components thinking it might alter the css class but that didn't seem to work.

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

Any feedback on how best to do this?


回答1:


You should be using the style attribute, that is the purpose of it.

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

const style = {
    width:  this.calcWidth()  + 'px',
    height: this.calcHeight() + 'px',
};

<div className={classLevelStyles} style={style} />



回答2:


You could try CSS custom properties on the CSS properties that are dynamic (eg, width and height):

// cell.css

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

Then you can supply the values of the CSS variables [in a parent container (CSS variables also cascade down)]:

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


来源:https://stackoverflow.com/questions/41503150/adding-style-attributes-to-a-css-class-dynamically-in-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!