The react of CSS

Video Tutorial Address

  1. Introduce external CSS

Create a home. The CSS

.title {
    border: 4px solid black;
}

#title {
    border: 4px solid black;
}
Copy the code

Importing CSS files

import React, {Component} from "react";
import '.. /home.css'

export default class Home extends Component<any.any> {

    render() {
        return (
            <>
                <div
                    id='title'
                    className='title'
                >
                    home page
                </div>
            </>)}}Copy the code

Import external CSS files. You can use the CSS as className or ID

  1. Inline CSS styles

    The CSS attribute names in TSX are small hump names

    import React, {Component} from "react";
    
    export default class Home extends Component<any.any> {
    
        render() {
            return (
                <>
                    <div
                        style={{
                            backgroundColor: 'red'}} >
                        home page
                    </div>
                </>)}}Copy the code
  2. Computing CSS styles

React to update the UI, you need to change the state

Define the state

interface IState {
    width: number
}
Copy the code

State is combined with the CSS

                <div
                    className={this.state.width > 550 ? 'title' : ' '}
                    style={{
                        width: `The ${this.state.width}px`.backgroundColor: 'red'
                    }}
                >
                    home page
                </div>
Copy the code

Update the state

    change = () = > {
        this.setState((state, props) = > ({
            width: state.width + 10}}))Copy the code

The final result

import React, {Component} from "react";
import '.. /home.css'
import {Button} from "antd";

interface IState {
    width: number
}

export default class Home extends Component<any.IState> {

    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            width: 500
        }
    }

    change = () = > {
        this.setState((state, props) = > ({
            width: state.width + 10}}))render() {
        return (
            <>
                <div
                    className={this.state.width >550? 'title' : ''} style={{ width: `${this.state.width}px`, backgroundColor: 'red' }} > home page</div>
                <Button type='primary' onClick={this.change}>change</Button>
            </>)}}Copy the code

We updated state, and the corresponding CSS styles changed accordingly