Recently wrote react in the application, and before the map is always simple, direct use of inline style. Taking advantage of free, summarize react style approach better except inline style.
1.classname library
Assembly is provided to facilitate dynamic className.
impoert React, { Componet } from 'react'; |
CSS Modules
Components to achieve local scope and style module dependencies.
Usage:
webpack the css-loader built CSS Modules function, so use CSS Modules must first enable css Modules in webpack configuration, as follows
css?modules&localIdentName=[name]__[local]-[hash:base64:5] |
Which is the plus modules enabled, localIdentName is set naming style.
Then the assembly css style file import will come to use.
.normal { |
Other notes
Global Style: CSS Module defaults to the local style, the style that is topical: local parcels, generated css name attached a string of random numbers, in order to achieve localized style.
You can use: global to achieve global style.:global(.btn) {
…
}
// more than one syle in gloabl
:global {
.normal{
...
}
.danger{
...
}
}- Style reuse: use compose
{.base |
At this time, using the normal style element or component actually generates two class.
CSS Modules will convert class names associated with style, that will only change the class selector. So id selector or selectors other attributes are not transformed style css modules.
CSS Mdoules combined application in classNames react in:
...
import className from 'classnames';
import styles from './styles.css';
class Dialog extends Component {
render() {
const cx = classNames({
confirm: !this.state.disabled,
disabledConfirm: this.state.disabled,
});
return (
<div className={styles.root}>
<a className={styles[cx]}>Confirm</a>
</div>
)
}
}Binding react-css-modules library avoid entering styles.xx.
//....
import CSSModules from 'react-css-modules';
//...
return (
<div styleName={root}>
<a styleName={cx}>Confirm</a>
</div>
)
export default CSSModules(Dialog, styles);
其它:
ts中import css文件的时候报错。
解决方法:增加一个module definition告诉typescript可以import css文件。
|
原文:大专栏 React中的样式处理