React style treatment of

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';
import classNames from 'classnames';

class extends Component {
render() {
const btnClass = classNames({
'btn': true,
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered,
});
return <button className={btnClass}>{this.props.label}</button>
}
}
  1. 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 {
color: #eee;
}
import style from './styles.css';
class Button extends Component {
render(){
return <button className={style.normal}></button>
}
}

Other notes

  1. 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{
    ...
    }
    }
    1. Style reuse: use compose
{.base 
// common style
}
called .Normal {
composes: Base;
// Normal unique style
}

At this time, using the normal style element or component actually generates two class.

  1. 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.

  2. 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>
    )
    }
    }
  3. 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文件。


declare module '*.css' {
const content: any;
export default content;
}

原文:大专栏  React中的样式处理


Guess you like

Origin www.cnblogs.com/chinatrump/p/11614954.html