第1章、react基础知识;

news2025/5/25 17:30:54

一、react学习前期准备;

1、基本概念;

  • 前期的知识准备:

    1.javascript、html、css;

    2.构建工具:Webpack:https://yunp.top/init/p/v/1

    3.安装node:npm:https://yunp.top/init/p/v/1

    4.cnpm命令:http://npm.taobao.org/

  • 官方文档:https://reactjs.org/docs/hello-world.html

二、react jsx语法;

1、jsx语法介绍;

  • 遇到<>按照HTML语法解析,遇到{}按照JavaScript

三、react元素渲染;

import React from "react"
import Home from "./Home"
import MyNav from "./MyNav"
import StateComponent from "./StateComponent";
import ComponentLife from "./ComponentLife"
import SetStateDemo from "./setStateDemo"
import IfDemo from "./ifDemo"
import KeyDemo from "./KeyDemo"
import FormDemo from "./FormDemo"
import RefsAndDOM from "./RefsAndDOM"
import RefsForm from "./RefsForm"
import Parent from "./components/parent"
import Compose from "./compose"
import PropsTypeDemo from "./PropsTypeDemo"

// 用类的形式创建组件,Hook形式
class App extends React.Component{

    constructor(){
        super();
        this.state = {
            title:"文本1"
        }
    }

    clickChange = (data) =>{
        this.setState({
            title:data
        })
    }

    // 渲染函数
    render(){

        // const nav1 = ["首页","视频","学习"];
        // const nav2 = ["WEB","Java","Node"];

        return(
            <div>
                {
                    /* 
                        <h1>Hello React Component</h1>
                        <h3>学习React,最重要的是,心态要好!</h3>
                        
                        <Home />

                        <MyNav nav={ nav1 } title="路径导航"/>

                        <MyNav nav={ nav2 } title="学习导航"/> 
                    */
                }

                {/* <StateComponent /> */}

                {/* <ComponentLife title={ this.state.title } clickChanges={ this.clickChange }/> */}

                {/* <SetStateDemo /> */}

                {/* <IfDemo /> */}

                {/* <KeyDemo /> */}

                {/* <FormDemo /> */}

                {/* <RefsAndDOM /> */}

                {/* <RefsForm /> */}

                {/* <Parent /> */}

                {
                    /*
                    <Compose>
                        <div>我是组合效果</div>
                    </Compose> 
                    */
                }

                { 
                  <PropsTypeDemo />
                }
         
            </div>
        )
    }
}

export default App

四、react组件基础之创建组件;

import React from "react"

export default class Home extends React.Component{

    constructor(props){
        super(props);
        // this.clickHandler = this.clickHandler.bind(this);
    }

    clickHandler(element,event){
        // this无指向
        // console.log(this);
        console.log(element,event);
    }

    // apply call bind:面试常见问题
    render(){
        const names = ['iwen','ime'];
        return(
            <div>
                Home  
                {/* <button onClick={ this.clickHandler.bind(this) }>按钮</button> */}
                {/* <button onClick={ this.clickHandler }>按钮</button> */}
                {/* <button onClick={ (e) => {this.clickHandler(e)}}>按钮</button> */}
                <ul>
                    {
                        names.map((element,index) => {
                            // return <li onClick={ this.clickHandler.bind(this,element) } key={index}>{ element }</li>
                            return <li onClick={ (e) => this.clickHandler(element, e) } key={index}>{ element }</li>
                        })
                    }
                </ul>
            </div>
        )
    }
}

五、react props属性;

import React from "react"

// props不可以被修改
export default class MyNav extends React.Component{
    render(){
        return(
            <div>
                {/* jsx语法 */}
                <h3>{ this.props.title }</h3>
                <ul>
                    {
                        this.props.nav.map((element,index) =>{
                            return <li key={index}>{ element }</li>
                        })
                    }
                </ul>
            </div>
        )
    }
}

六、react state 状态;

import React from "react"

export default class StateComponent extends React.Component{
    /**
     * 组件中的状态:state
     * 以前我们操作页面的元素的变化,都是修改DOM,操作DOM
     * 但是有了React优秀的框架,我们不在推荐操作DOM,页面元素的改变使用State进行处理
     */

    constructor(props){
        super(props);
        // 定义
        this.state = {
            count:10,
            flag:true
        }
    }

    increment(){
        // setState
        this.setState({
            count:this.state.count+=1
        })
    }

    decrement(){
        this.setState({
            count:this.state.count-=1
        })
    }

    clickHandler = () =>{
        console.log(this);
    }

    render(){
        let showView = this.state.flag ? '我是孙悟空' : '我是假的孙悟空'
        return(
            <div>
                <h3>组件的State</h3>
                <p>{ this.state.count }</p>
                <button onClick={ this.increment.bind(this) }>增加</button>
                <button onClick={ this.decrement.bind(this) }>减少</button>
                <button onClick={ this.clickHandler }>关于this</button>
                <p>{ showView }</p>
            </div>
        )
    }
}

七、react组件生命周期函数;

1、基本概念;

  • componentWillMount 在组件渲染之前执行;

  • componentDidMount 在组件渲染之后执行;

  • shouldComponentUpdate 返回true和false,true代表允许改变,false代表不允许改变;

  • componentWillUpdate:数据在改变之前执行(state,props);

  • componentDidUpdate:数据修改完成(state,props);

  • componentWillReveiceProps:props发生改变执行;

  • componentWillUnmount 组件卸载前执行;

2、代码;

import React from "react"

export default class ComponentLife extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            count:10
        }
    }

    componentWillMount(){
        console.log("componentWillMount");
    }

    componentDidMount(){
        console.log("componentDidMount");
    }

    shouldComponentUpdate(){
        console.log("shouldComponentUpdate");
        return true;
    }

    componentWillUpdate(){
        console.log("componentWillUpdate");
    }

    componentDidUpdate(){
        console.log("componentDidUpdate");
    }

    componentWillReceiveProps(){
        console.log("componentWillReceiveProps");
    }

    componentWillUnmount(){
        console.log("componentWillUnmount");
    }

    changeHandler = () =>{
        this.setState({
            count:this.state.count+=1
        })
    }

    clickChange = () => {
        this.props.clickChanges('我是儿子的数据');
    }

    render(){
        const { count } = this.state;
        return(
            <div>
                生命周期函数:{ count } - { this.props.title }
                <button onClick={ this.changeHandler }>修改</button>
                <button onClick={ this.clickChange }>修改title</button>
            </div>
        )
    }
}

八、react setState 是同步还是异步;

import React from "react"

export default class SetStateDemo extends React.Component{

    constructor(){
        super();
        this.state = {
            count:0
        }
    }

    // 01.异步
    increment1(){
        this.setState({
            count:this.state.count+1
        });
        console.log(this.state.count);
    }

    // 02.官网的解决方案
    increment2(){
        this.setState({
            count:this.state.count+1
        },() => {
            console.log(this.state.count);
        })
    }

    // 03.利用 promise 和 async/await 把异步改成同步
    async increment3(){
        await this.setStateAsync({count:this.state.count+1});
        console.log(this.state.count);
    }
    setStateAsync(state){
        return new Promise((resolve) =>{
            this.setState(state,resolve);
        })
    }

    render(){
        return(
            <div>
                setState同步还是异步问题
                <p>{ this.state.count }</p>
                <button onClick={ this.increment1.bind(this) }>修改1</button>
                <button onClick={ this.increment2.bind(this) }>修改2</button>
                <button onClick={ this.increment2.bind(this) }>修改3</button>
            </div>
        )
    }
}

九、react 条件渲染;

import React from "react"

export default class IfDemo extends React.Component {
    /**
     * 常用的应用常见:
     *  1.对视图条件进行切换
     *  2.做缺省值
     */

    constructor() {
        super();
        this.state = {
            isLogin: false,
            names: ["ime"]
        }
    }
    clickHandler = () => {
        this.setState({
            isLogin: true
        })
    }

    render() {
        const { names } = this.state;
        let showView = this.state.isLogin ? <div>iwen</div> :  <div>请登录</div>;

        return (
            <div>
                条件渲染:{showView}
                <button onClick={this.clickHandler}>登录</button>

                {
                    names.length > 0 ?
                        <div>
                            {
                                names.map((element, index) => {
                                    return <p key={index}>{element}</p>
                                })
                            }
                        </div>
                        :
                        <div>请等待数据正在请求....</div>
                }
                
            </div>
        )
    }
}

十、react列表渲染key;

1、基本概念;

  • 前key代表唯一索引,索引没有变化ui不会重绘,只有key发生变化才会发生重绘;

import React from "react"

export default class KeyDemo extends React.Component{

    constructor(){
        super();
        this.state = {
            userinfo:[
                {
                    name:"frank",
                    age:20,
                    sex:"男",
                    jobs:['后端']
                }
            ]
        }
    }

    clickHandler = () =>{
        this.setState({
            userinfo:this.state.userinfo.concat([{
                name:"sakura",
                age:30,
                sex:"女",
                jobs:['前端']
            }])
        })
    }

    render(){
        return(
            <div>
                <ul>
                    {
                        this.state.userinfo.map((element,index) =>{
                            return(
                                <li key={ index }>
                                    <span>姓名:{ element.name }</span>
                                    <span>年龄:{ element.age }</span>
                                    <span>性别:{ element.sex }</span>
                                    <div>
                                        职业:
                                        {
                                           element.jobs.map((childElement,childIndex) =>{
                                               return <span key={ childIndex }>
                                                         { childElement }
                                                      </span>
                                            })
                                        }
                                    </div>
                                </li>
                            )
                        })
                    }
                </ul>
                <button onClick={ this.clickHandler }>添加数据</button>
            </div>
        )
    }
}

十一、react表单受控组件;

import React from "react"

export default class FormDemo extends React.Component{

    constructor(){
        super();
        // 表单的值是受控组件
        this.state = {
            value:""
        }
    }

    handleSubmit = (e) =>{
        // 表单事件默认跳转,阻止事件
        e.preventDefault();
        console.log(this.state.value);
    }

    onChangeHandler = (e) =>{
        this.setState({
            value:e.target.value
        })
    }

    render(){
        return(
            <div>
                <form onSubmit={this.handleSubmit}>
                    <input type="text" value={ this.state.value } 
                           onChange={ this.onChangeHandler }/>
                    <input type="submit" value="提交"></input>
                </form>
            </div>
        )
    }
}

十二、React RefsDom;

import React from "react"

export default class RefsAndDOM extends React.Component{

    constructor(){
        super();
        // 创建一个获取dom对象
        this.HelloDiv = React.createRef();
        this.spanText = React.createRef();
    }

    // ui已经渲染完成,dom是存在
    componentDidMount(){
        this.HelloDiv.current.style.color = "red";

        this.spanText.current.style.color = "red";
    }

    render(){
        return(
            <div>
                <div ref={ this.HelloDiv }>
                    Hello
                </div>

                <div ref={ this.spanText }>
                    <span>这是文本信息</span>
                </div>
            </div>
        )
    }
}

十三、react表单非受控组件;

import React from "react"

export default class RefsForm extends React.Component{

    constructor(){
        super();
        this.username = React.createRef();
        this.password = React.createRef();
    }

    clickHandler = (e) =>{
        console.log("username",this.username);
        console.log(this.username.current.value);
        console.log(this.password.current.value);
    }

    render(){
        return(
            <div>
                <input type="text" ref={ this.username }/>
                <input type="text" ref={ this.password }/>
                <button onClick={ this.clickHandler }>提交</button>
            </div>
        )
    }
}

十四、react 状态提升;

// 父组件:parent
import React from "react"
import Child1 from "./child1"
import Child2 from "./child2"

export default class Parent extends React.Component{
    constructor(){
        super();
        this.state = {
            money:1
        }
    }
    changeHandler(e){
        this.setState({
            money:e.target.value
        })
    }  
    render(){
        return(
            <div>
                <div>
                    parent:
                    <input type="text" value={ this.state.money } 
                           onChange={this.changeHandler.bind(this)} />
                </div>
                <div>
                    <Child1 money={ this.state.money }/>
                </div>
                <div>
                    <Child2 money={ this.state.money }/>
                </div>
            </div>
        )
    }
}
// 子组件1:child1
import React from "react"

export default class Child1 extends React.Component{
    constructor(){
        super();
        this.state = {
            input1:0
        }
    }
    componentDidMount(){
        this.setState({
            input1:this.props.money
        })
    }
    changeHandler(e){
        this.setState({
            input1:e.target.value
        })
    }
    render(){
        return(
            <div>
                人民币:
                <span>{this.props.money}</span>
                <input type="text" value={ this.state.input1 } 
                       onChange={ this.changeHandler.bind(this) }/>
            </div>
        )
    }
}
// 子组件2
import React from "react"

export default class Child2 extends React.Component {

    constructor(){
        super();
        this.state = {
            input2:0
        }
    }

    componentDidMount(){
        this.setState({
            input2:this.props.money * 7
        })
    }

    changeHandler(e){
        this.setState({
            input2:e.target.value
        })
    }

    render() {
        return (
            <div>
                美元
                <span>{this.props.money * 7}</span>
                <input type="text" value={ this.state.input2 } 
                       onChange={this.changeHandler.bind(this)} />
            </div>
        )
    }
}

十五、react 组件组合;

import React from "react"

/**
    <Compose>
        <div>我是组合效果</div>
    </Compose> 
**/

export default class Compose extends React.Component{
    render(){
        return(
            <div>
                哈哈哈:{ this.props.children }
            </div>
        )
    }
}

十六、react PropsType 组件验证;

import React from 'react'
import PropTypes from 'prop-types';

export default class PropsTypeDemo extends React.Component{
    render(){
        return(
            <div>
                Hello:{ this.props.title }
            </div>
        )
    }
}

// PropsTypeDemo.propTypes = {
//     title:PropTypes.number.isRequired
// }

PropsTypeDemo.propTypes = {
    title:PropTypes.string.isRequired
}

// PropsTypeDemo.defaultProps = {
//     title:'默认值'
// }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1593237.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java基础-知识点03(面试|学习)

Java基础-知识点03 String类String类的作用及特性String不可以改变的原因及好处String、StringBuilder、StringBuffer的区别String中的replace和replaceAll的区别字符串拼接使用还是使用StringbuilderString中的equal()与Object方法中equals()区别String a new String("a…

论文笔记:A Simple and Effective Pruning Approach for Large Language Models

iclr 2024 reviewer 评分 5668 1 intro 大模型网络剪枝的paper 在努力保持性能的同时&#xff0c;舍弃网络权重的一个子集现有方法 要么需要重新训练 这对于十亿级别的LLMs来说往往不现实要么需要解决依赖于二阶信息的权重重建问题 这同样可能带来高昂的计算成本——>引入…

ELK、ELKF企业级日志分析系统介绍

前言 随着企业级应用系统日益复杂&#xff0c;随之产生的海量日志数据。传统的日志管理和分析手段&#xff0c;难以做到高效检索、实时监控以及深度挖掘潜在价值。在此背景下&#xff0c;ELK日志分析系统应运而生。"Elastic" 是指 Elastic 公司所提供的一系列与搜索…

IDEA Warnings:SQL dialect is not configured.

springboot项目XxxMapper.xml文件打开后显示warnings&#xff1a;SQL dialect is not configured......&#xff08;翻译&#xff1a;未配置SQL语言。&#xff09; 大概意思是没有在IDEA中配置当前sql是MySQl、Oracle还是MariaDB等语言。 配置一下就好&#xff1a; 完了&#…

C语言: 字符串函数(下)

片头 在上一篇中,我们介绍了字符串函数。在这一篇章中&#xff0c;我们将继续学习字符串函数&#xff0c;准备好了吗&#xff1f;开始咯&#xff01; 1.strncpy函数 1.1 strncpy函数的用法 strncpy是C语言中的一个字符串处理函数&#xff0c;它用于将一个字符串的一部分内容…

基于SpringBoot实现的在线拍卖系统

系统开发环境 编程语言&#xff1a;Java数据库&#xff1a;MySQL容器&#xff1a;Tomcat工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统实现 管理员功能模块 首页 修改密码 用户管理 商品类型管理 拍卖商品 竞拍公告 轮播图 历史竞拍管理 竞拍订单管理 留言板管理 用户…

selenium添加代理(有账号密码)

以下为各种尝试的记录&#xff0c;正确实现可直接参考最后一条&#xff01; 1&#xff0c;导入Proxy库来添加capabilities属性&#xff1a;可以访问网站&#xff0c;但ip还是本机ip from selenium import webdriver from selenium.webdriver.chrome.options import Options f…

【Java探索之旅】方法重载 递归

&#x1f3a5; 屿小夏 &#xff1a; 个人主页 &#x1f525;个人专栏 &#xff1a; Java编程秘籍 &#x1f304; 莫道桑榆晚&#xff0c;为霞尚满天&#xff01; 文章目录 &#x1f4d1;前言一、方法重载1.1 为什么要有方法重载1.2 方法重载的概念与使用1.3 方法签名 二、递归2…

网络篇05 | 应用层 http/https

网络篇05 | 应用层 http/https 01 HTTP请求报文协议&#xff08;Request&#xff09;1&#xff09;Request简述2&#xff09;请求行&#xff08;首行&#xff09;3&#xff09;请求头&#xff08;Request Headers&#xff09;4&#xff09;空行5&#xff09;正文&#xff08;Re…

2024年4月8日腾讯云故障复盘及情况说明

2024年4月8日15点23分&#xff0c;腾讯云团队收到告警信息&#xff0c;云API服务处于异常状态&#xff1b;随即在腾讯云工单、售后服务群以及微博等渠道开始大量出现腾讯云控制台登录不上的客户反馈。 经过故障定位发现&#xff0c;客户登录不上控制台正是由云API异常所导致。云…

commit 信息风格迥异、难以阅读,如何规范?

大家好&#xff01;最近很长时间没有更新了&#xff0c;由于加入新团队新的项目组参与新的工作&#xff0c;导致博客创造搁置了一段时间&#xff0c;今天来记录一下我最近学习到的规范。 怎么写出符合 Angular 规范的 Commit Message 呢&#xff1f; 这是我们团队规定的规范。…

【免安装的MATLAB--MATLAB online】

目录&#xff1a; 前言账号的注册图片处理的示例准备图片脚本函数 总结 前言 在计算机、数学等相关专业中&#xff0c;或多或少都会与MATLAB产生藕断丝连的联系&#xff0c;如果你需要使用MATLAB&#xff0c;但是又不想要安装到自己的电脑上&#xff08;它实在是太大了啊&#…

如何防止软件过度封装和抽象?

一、合适的软件架构 构建可读性强、高内聚、低耦合的软件架构是软件工程中的重要原则&#xff0c;这有助于提高代码的维护性、扩展性和复用性。以下是一些实践方法&#xff1a; 1. **模块化设计**&#xff1a;将系统划分为一系列职责单一、功能明确的模块或组件&#xff0c;每…

【新版】系统架构设计师 - 知识点 - 面向对象开发方法

个人总结&#xff0c;仅供参考&#xff0c;欢迎加好友一起讨论 文章目录 架构 - 知识点 - 面向对象开发方法面向对象开发方法面向对象的分析需求模型分析模型 面向对象的设计 用例模型关系、UML事务关系、类的关系 架构 - 知识点 - 面向对象开发方法 面向对象开发方法 分析阶段…

深度学习体系结构——CNN, RNN, GAN, Transformers, Encoder-Decoder Architectures算法原理与应用

1. 卷积神经网络 卷积神经网络&#xff08;CNN&#xff09;是一种特别适用于处理具有网格结构的数据&#xff0c;如图像和视频的人工神经网络。可以将其视作一个由多层过滤器构成的系统&#xff0c;这些过滤器能够处理图像并从中提取出有助于进行预测的有意义特征。 设想你手…

springboot数字化智慧城市管理系统源码

目录 ​系统开发环境 系统功能模块 系统特点 1、智慧城管移动端 2、案件受理 3、AI视频智识别分析 系统应用价值 1、提升案件办理效率 2、提升监管效能 3、提升行政执法水平 4、推进行政执法创新 智慧城管综合执法办案系统功能 现场移动执法 一般程序案件的网上办…

“Plandex:AI编程引擎革新,高效应对复杂任务“

Plandex Plandex 是一个开源的、基于终端的AI编程引擎&#xff0c;用于处理复杂任务。它通过长期运行的代理来完成跨越多个文件和多个步骤的任务&#xff0c;将大型任务分解为更小的子任务&#xff0c;然后逐个实现&#xff0c;直到完成整个工作。这有助于用户处理待办事项、处…

Mapmost Alpha:开启三维城市场景创作新纪元

&#x1f935;‍♂️ 个人主页&#xff1a;艾派森的个人主页 ✍&#x1f3fb;作者简介&#xff1a;Python学习者 &#x1f40b; 希望大家多多支持&#xff0c;我们一起进步&#xff01;&#x1f604; 如果文章对你有帮助的话&#xff0c; 欢迎评论 &#x1f4ac;点赞&#x1f4…

:app debug:armeabi-v7a failed to configure C/C++

报错信息 由于刚换电脑不久&#xff0c;新建native c工程时&#xff0c;出现报错如下&#xff1a; :app debug:armeabi-v7a failed to configure C/C null java.lang.NullPointerExceptionat com.android.build.gradle.tasks.CmakeQueryMetadataGenerator.getProcessBuilder(…

Linux:环境基础开发工具使用

文章目录 前言1.Linux下的软件安装1.1 什么是软件包1.2 如何安装软件1.3 如何卸载软件 2.vim2.1 vim的基本概念2.2 vim的基本操作2.3 vim正常模式命令集2.4 vim末行模式命令集2.5 vim的操作总结 3.Linux下的编译器&#xff1a;gcc3.1 gcc的使用3.2 gcc是如何工作的3.2.1 预处理…