日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語言 正文

react裝飾器與高階組件及簡(jiǎn)單樣式修改的操作詳解_React

作者:勇敢*牛牛 ? 更新時(shí)間: 2022-11-14 編程語言

使用裝飾器調(diào)用

裝飾器 用來裝飾類的,可以增強(qiáng)類,在不修改類的內(nèi)部的源碼的同時(shí),增強(qiáng)它的能力(屬性或方法)

裝飾器使用@函數(shù)名寫法,對(duì)類進(jìn)行裝飾,目前在js中還是提案,使用需要配置相關(guān)兼容代碼庫(kù)。

react腳手架創(chuàng)建的項(xiàng)目默認(rèn)是不支持裝飾器,需要手動(dòng)安裝相關(guān)模塊和添加配置文件

??安裝相關(guān)模塊

yarn add -D customize-cra react-app-rewired ?@babel/plugin-proposal-decorators

??修改package.json文件中scripts命令

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  }

??在項(xiàng)目根目錄中添加config-overrides.js配置文件

此文件可以理解為就是webpack.config.js的擴(kuò)展文件

const { resolve } = require('path')
const { addDecoratorsLegacy, override } = require('customize-cra')
// 增強(qiáng)自定義給webpack添加相關(guān)配置
const custom = () => config => {
  config.resolve.alias['@'] = resolve('./src')
  return config
}
module.exports = override(addDecoratorsLegacy(), custom())

一般加上這個(gè)就行:

// 增量配置當(dāng)前項(xiàng)目中的webpack配置,建議在react18中不要用
// 建議在react18中也不要用裝飾器
// override 方法,如果webpack中有此配置則,覆蓋,如果沒有則添加
const { addDecoratorsLegacy, override } = require('customize-cra')
// 追加上一個(gè)裝飾器
module.exports = override(addDecoratorsLegacy())

裝飾器的使用

裝飾類

裝飾函數(shù),在裝飾時(shí)它沒有寫小括號(hào),target它就是當(dāng)前你裝飾的類

添加靜態(tài)方法/屬性:

不是成員方法

const handle = target =>{
    target.run = ()=>{
        console.log("run");
    }
}
@handle
class Demo {};
const d = new Demo();
Demo.run();

添加成員方法/屬性:

const handle = target =>{
    target.prototype.run = ()=>{
        console.log("run");
    }
}
@handle
class Demo {};
const d = new Demo();
d.run();

裝飾器加上了小括號(hào),則定義函數(shù)時(shí)一定要返回一個(gè)新函數(shù)

const handle = (msg) => target =>{
    target.prototype.run = ()=>{
        console.log("run",msg);
    }
}
@handle("我愛你")
class Demo {};
const d = new Demo();
d.run();

裝飾成員屬性

裝飾器裝飾成員屬性,裝飾時(shí)沒有寫小括號(hào)

裝飾器裝飾成員屬性,裝飾時(shí)沒有寫小括號(hào)
target 裝飾的類的實(shí)例 new Demo  this
key 當(dāng)前的成員屬性名稱  username
description 就是當(dāng)前屬性在對(duì)象中它的描述 Object.defineProperty
const handle = (target, key, description) => {
  // 設(shè)置當(dāng)前屬性為只讀屬性
  // description.writable = false
  console.log(target, key, description)
}
class Demo {
  @handle
  username = 'abc'
}

高階組件

定義高階組件,用來進(jìn)行全局布局

1.它就是一個(gè)函數(shù)

2.參數(shù)首字母大寫,因?yàn)槟銈魅氲氖且粋€(gè)組件,在react中組件的調(diào)用必須首字母大寫

3.返回一個(gè)組件

簡(jiǎn)單的樣式修改

一、沒有使用cssModule時(shí),只能直接導(dǎo)入

import './style.css'
<div className="todo-title">任務(wù)列表</div>

注意手動(dòng)添加標(biāo)識(shí)符

例如:

.todo-title {
  color: red;
}

二、 在react中create-react-app工程,它內(nèi)置了cssModule功能,但是文件后綴一定要有xxx.module.css/scss

如果有scss文件,必須得安裝yarn add sass

import styles from './style.module.css'

引用:

<div className={styles.title}>任務(wù)列表</div>
<span className={done ? style.title : ''}>{title}</span>

原文鏈接:https://niuniu.blog.csdn.net/article/details/126984533

欄目分類
最近更新