首页 > 其他分享 >第五章、react高级

第五章、react高级

时间:2022-11-30 23:23:06浏览次数:57  
标签:axios const dayjs 高级 react 第五章 import config

目录

十一、AntDesign组件库

1、react中添加class-使用第三方库classnames
import React, {PureComponent} from "react";
// 安装:npm i -S classnames
import classNames from "classnames";

export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isActive: true
    }
  }

  render() {
    const {isActive} = this.state
    return (<div>
      {/* 1、原生react中添加class方法 */}
      <h2 className={"title active"}>我是标题1</h2>
      <h2 className={"title" + (isActive ? " active" : "")}>我是标题2</h2>
      <h2 className={["title", isActive ? "active" : ""].join(" ")}>我是标题3</h2>
      {/* 2、classnames库添加class */}
      <h3 className={classNames("title", "active")}>我是标题1</h3>
      <h3 className={classNames({"title": true, "active": true})}>我是标题1</h3>
      <h3 className={classNames(["title", {"active": true}])}>我是标题1</h3>
    </div>)
  }
}
2、antdesign简介
  • src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './layout/App';
import "./styles/index.css"
import 'dayjs/locale/zh-cn';
import {ConfigProvider} from "antd"
import locale from 'antd/locale/zh_CN';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ConfigProvider locale={locale}>
  <App/>
</ConfigProvider>);
  • src/layout/App.js
import React, {PureComponent} from "react";
// 安装:npm i -S antd
import {Button, DatePicker} from "antd"
// 安装图标:npm i -S @ant-design/icons
import {PoweroffOutlined} from "@ant-design/icons"
// 安装:npm i -S dayjs
import dayjs from "dayjs"

export default class App extends PureComponent {
  render() {
    return (<div>
      <Button type={"primary"} icon={<PoweroffOutlined/>}>按钮</Button>
      <DatePicker defaultValue={dayjs().add(10, "day")} allowClear={false}/>
    </div>)
  }
}
3、认识craco
  • package.json
{
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  }
}
  • craco.config.js
// 安装:npm i -D @craco/craco
module.exports = {};
4、自定义主题
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './layout/App';
import "./styles/index.css"
import 'dayjs/locale/zh-cn';
import {ConfigProvider} from "antd"
import locale from 'antd/locale/zh_CN';

const root = ReactDOM.createRoot(document.getElementById('root'));
// 自定义主题
root.render(<ConfigProvider
  locale={locale}
  theme={{
    token: {
      colorPrimary: '#1DA57A'
    }
  }}>
  <App/>
</ConfigProvider>);
5、配置别名
  • craco.config.js
const path = require("path")

module.exports = {
  webpack: {
    alias: {
      // webstorm需要配置jsconfig.json才会有路径别名提示
      "@": path.resolve(__dirname, "src")
    }
  }
};
  • jsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    }
  }
}
6、案例
  • src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './layout/App';
import "./styles/index.css"
import {ConfigProvider} from "antd"
import locale from 'antd/locale/zh_CN';
import dayjs from "dayjs";
import 'dayjs/locale/zh-cn';
import relativeTime from "dayjs/plugin/relativeTime"

dayjs.locale("zh-cn")
// dayjs插件
dayjs.extend(relativeTime)

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ConfigProvider locale={locale}>
  <App/>
</ConfigProvider>);
  • src/layout/App.js
import React, {PureComponent} from "react";
import CommonInput from "@/components/CommonInput";
import CommonItem from "@/components/CommonItem";

export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      commentList: []
    }
  }

  render() {
    return (<>
      {
        this.state.commentList.map((item, index) => {
          return <CommonItem comment={item}
                             key={item.id}
                             removeItem={e => this.removeComment(index)}/>
        })
      }
      <CommonInput submitComment={this.submitComment.bind(this)}/>
    </>)
  }

  submitComment(info) {
    this.setState({
      commentList: [...this.state.commentList, info]
    })
  }

  removeComment(index) {
    const newCommentList = [...this.state.commentList]
    newCommentList.splice(index, 1)
    this.setState({
      commentList: newCommentList
    })
  }
}
  • src/components/CommonInput.js
import React, {PureComponent} from "react";
import {Input, Button} from "antd";
import dayjs from "dayjs";

export default class CommonInput extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      content: ""
    }
  }

  render() {
    return (<div>
      <Input.TextArea rows={4}
                      value={this.state.content}
                      onChange={e => this.handleChange(e)}/>
      <Button type={"primary"} onClick={e => this.addComment()}>添加评论</Button>
    </div>)
  }

  handleChange(event) {
    this.setState({
      content: event.target.value
    })
  }

  addComment() {
    if (this.state.content) {
      const commentInfo = {
        id: dayjs().valueOf(),
        avatar: "https://himg.bdimg.com/sys/portraitn/item/public.1.ad0d64c5.9sfie_WOcRvlqCxH_2MKnQ",
        nickname: "斧王",
        datetime: dayjs(),
        content: this.state.content
      }
      this.props.submitComment(commentInfo)
      this.setState({
        content: ""
      })
    }
  }
}
  • src/components/CommonItem.js
import React, {PureComponent} from "react";
// 安装(使用过高版本会报错,与antd版本一致):npm i @ant-design/compatible
import {Comment} from "@ant-design/compatible"
import {Avatar, Tooltip} from "antd"
import {DeleteOutlined} from "@ant-design/icons";

export default class CommonItem extends PureComponent {
  render() {
    const {nickname, avatar, content, datetime} = this.props.comment
    return (<div>
      <Comment
        author={<a href="/#">{nickname}</a>}
        avatar={<Avatar src={avatar} alt={nickname}/>}
        content={<p>{content}</p>}
        datetime={<Tooltip title={datetime.format("YYYY-MM-DD")}>
          <span>{datetime.fromNow()}</span>
        </Tooltip>}
        actions={[
          <span onClick={e => this.removeItem()}><DeleteOutlined/>删除</span>
        ]}
      />
    </div>)
  }

  removeItem() {
    this.props.removeItem()
  }
}

十二、axios库的使用

1、axios的基本使用
import React, {PureComponent} from "react";
import axios from "axios"

export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      products: []
    }
  }

  /**
   * 1、axios:ajax i/o system
   * 2、安装:npm i -S axios
   * 3、请求测试网站:https://httpbin.org
   * 4、使用方式:
   *     - axios(config)
   *     - axios.request(config):其它方式都是调用此种方式
   *     - axios.get(url[, config]):查
   *     - axios.delete(url[, config]):删
   *     - axios.head(url[, config])
   *     - axios.post(url[, data[, config]]):增
   *     - axios.put(url[, data[, config]]):改
   *     - axios.patch(url[, data[, config]])
   */
  async componentDidMount() {
    // 默认get请求
    axios({
      url: "https://httpbin.org/get",
      params: {name: "冰龙", age: 18}
    }).then(res => {
      // 处理数据
      // this.setState({
      //   products: [...this.state.products, ...res]
      // })
    }).catch(console.log)

    const request1 = axios({
      url: "https://httpbin.org/post",
      data: {name: "神谕者", age: 19},
      method: "post"
    })

    const request2 = axios.get("https://httpbin.org/get", {
      params: {name: "白牛", age: 20}
    })

    try {
      const result = await axios.post("https://httpbin.org/post", {name: "火枪", age: 21})
      console.log(result)
    } catch (err) {
      console.log(err)
    }

    // Promise.all()
    axios.all([request1, request2]).then(([res1, res2]) => {
      console.log(res1, res2)
    })
    const p1 = new Promise(resolve => {
      setTimeout(() => {
        resolve("奇美拉")
      }, 1000)
    })
    const p2 = new Promise(resolve => {
      setTimeout(() => {
        resolve("狮鹫")
      }, 3000)
    })
    Promise.all([p1, p2]).then(res => {
      console.log(res)
    })
  }

  render() {
    return (<>
      APP
    </>)
  }
}
2、axios的配置信息
// 1、请求配置选项
// 2、响应结构信息
// 3、全局默认配置
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/**
 * 4、自定义实例默认配置:
 *     - 优先是请求的config参数配置:instance({baseURL: "111"})
 *     - 其次是实例的default中的配置:instance.defaults.baseURL = "222"
 *     - 再是创建实例时的配置:const instance = axios.create({baseURL: "333"})
 *     - 最后全局的配置:axios.defaults.baseURL = "444"
 */
const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
3、axios拦截器
  • src/layout/App.js
import React, {PureComponent} from "react";
import request from "@/utils/request"

export default class App extends PureComponent {
  componentDidMount() {
    request({
      url: "/get",
      params: {name: "小小", age: 18}
    }).then(console.log)
  }

  render() {
    return (<></>)
  }
}
  • src/utils/request.js
import axios from "axios"

const config = {
  development: {
    baseURL: "https://httpbin.org",
    timeout: 5000
  },
  production: {
    baseURL: "https://httpbin.org",
    timeout: 5000
  }
}
const instance = axios.create(config[process.env.NODE_ENV])

instance.interceptors.request.use(config => {
  // 1、发送网络请求时,在界面中间位置显示Loading的组件
  // 2、某一些请求要求用户必须携带token,如果没有携带,那么直接跳转到登录页面(router)
  // 3、params/data序列化的操作
  console.log("请求被拦截")
  return config
}, err => {
})

instance.interceptors.response.use(res => {
  return res.data
}, err => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        console.log("请求错误")
        break;
      case 401:
        console.log("未授权访问")
        break;
      default:
        console.log("其它错误信息")
    }
  }
  return err
})

export default instance

标签:axios,const,dayjs,高级,react,第五章,import,config
From: https://www.cnblogs.com/linding/p/16940143.html

相关文章

  • MYSQL高级语言(一)
    引言MySQL常用的sql语言为(增删改查),其中查最为常用,对MySQL数据库的查询,除了基本的查询外,有时候需要对查询的结果集进行处理。例如只取特定条数据、对查询结果进行排序......
  • MySQL高级SQL语句(二)
    表连接查询MYSQL数据库中的三种连接innerjoin(内连接):只返回两个表中联结字段相等的行(有交集的值)leftjoin(左连接):返回包括左表中的所有记录和右表中联结字段相等的......
  • Python高级-正则表达式-笔记
    1.re模块操作在Python中需要通过正则表达式对字符串进行匹配的时候,可以使用一个模块,名字为re1.re模块的使用过程#coding=utf-8#导入re模块importre#使用mat......
  • MYSQL高级语句二
    一、VIEW(视图)1、概念可以被当作是虚拟表或存储查询视图跟表格的不同是,表格中有实际储存资料,而视图是建立在表格之上的一个架构,它本身并不实际储存资料。临时表在用户......
  • Python高级-多任务协程-笔记
    为了更好的理解协程,可以翻阅上一篇​​ Python高级-多任务进程-笔记​​1.迭代器迭代是访问集合元素的一种方式。迭代器是一个可以记住遍历的位置的对象。迭代器对象从集合......
  • 第五章 插值与逼近
    5.1离散问题定义给定一组点\(\{x_i,y_i\}\quad(i=0,1,\cdots,n)\)并且\(x_0<x_1<\cdots<x_n\),若函数\(f(x)\)使得\(\qquadf(x_i)=y_i\quad(i=0,1,\cdots,n)\)成立,则......
  • React学习笔记,文档中的大部分代码都有注释
    React主要用于构建UI。你可以在React里传递多种类型的参数,如声明代码,帮助你渲染出UI、也可以是静态的HTMLDOM元素、也可以传递动态变量、甚至是可交互的应用组件。1.使用(......
  • Python高级-多任务线程-笔记
    1.多任务的概念什么叫“多任务”呢?简单地说,就是操作系统可以同时运行多个任务。打个比方,你一边在用浏览器上网,一边在听MP3,一边在用Word赶作业,这就是多任务,至少同时有3个任务......
  • React Native 单位详细说明
    之前在ReactNative笔记(二)中总结了一点,RN长宽单位默认对应DP:所谓与密度无关就是密度变化不引起物理尺寸的变化,这一点DP与RN官方说的一致.现在想想,也就是说1DP在物理尺寸上......
  • 2022助我拿到9个Offer的成功秘籍?MySQL高级调优笔记 冲就完了
    第一部分:MySQL常用对象=================Linux安装MySQL及启动MySQL对象-索引MySQL对象-视图MySQL对象-存储过程MySQL对象-触发器第二部......