CSS在React中使用的方式

92 阅读1分钟

一、React常见css使用方法

1、行内css

const inlineStyle = {
    width: "300px",
    height: "300px",
    backgroundColor: "#44014C" // 属性名为驼峰法
};

let Box = () => {
    return (
        <>
            <div className="box" style={inlineStyle}>
                this is a box
            </div>
        </>
    );
};

2、在组件中导入css文件

该种形式css样式,会作用于当前组件及其所有后代组件。

import "./index.less";
let Box = () => {
    return (
        <>
            <div className="box" style={inlineStyle}>
                this is a box
            </div>
        </>
    );
};
.box {
    color: aqua;
}

3、使用module.css文件

css文件作为一个模块,只作用在当前组件,不会影响后代组件。

import styles from "./index.module.less";
let Box = () => {
    return (
        <>
            <div className={`${styles.box} box`} style={inlineStyle}>
                this is a box
            </div>
        </>
    );
};

.box {
    font-size: 100px;
}

二、其他css问题

1、react中样式穿透

.box {
    font-size: 100px;
    :global(.box-child) {
        width: 200px;
        height: 100px;
        background-color: red;
    }
}