• React01


    React-day01 入门知识

    React介绍

    Facebook脸书-> Instagram照片墙 。 于2013年5月开源

    帮助开发者简洁、直观地构建高性能的UI界面

    • 高效:模拟Doument Object Model,减少DOM交互 (速度快)
    • 灵活:可以与已知的库配合使用
    • 声明式: 帮助开发者直观的创建UI
    • 组件化:把相似的代码通过封装成组件进行复用

    官网

    官方网站: https://reactjs.org/

    中文网站: https://doc.react-china.org/

    React开发环境初始化 SPA

    • react :React开发必备库
    • react-dom:web开发时使用的库,用于虚拟DOM,移动开发使用ReactNative

    脚手架初始化项目(方便,稳定)*

    • 执行初始化命令:

      #保证Node版本>=6
      npm install -g create-react-app
      create-react-app my-app
      
      cd my-app
      npm start
      ## 如果npm版本5.2.0+,可以使用npx进行初始化
      npx create-react-app my-app
      
      cd my-app
      npm start
      
    • npm和yarn命令对比

    通过webpack进行初始化

    步骤文档

    配置镜像地址

    • 查看当前镜像配置:

      npm config list

      npm config get registry

    • 设置当前镜像地址

      npm config set registry https://registry.npm.taobao.org/

      npm config set disturl https://npm.taobao.org/dist

    开发工具配置

    • 添加JavaScript语法支持
    • 安装开发插件: JavaScript,npm, markdown, Node.js, Reactjs

    元素渲染

    • 元素是构成React应用的最小单位

      import React from 'react';
      import ReactDOM from 'react-dom';
      
      const element = (
          <div>
              <h1>HaHa!</h1>
              <h2>Hello Itheima element</h2>
          </div>
      );
      
      // ReactDOM进行元素渲染
      ReactDOM.render(
          element,
          document.getElementById('root')
      );
      
    • React对JSX语法转换

      const element = (    
        <div className="eleClass">        
          HaHa!  
        </div>
      );
      

      转换js后

      const element = React.createElement(
        "div",
        { className: "eleClass" },
        "HaHa!"
      );
      

    组件及组件状态

    组件可以将界面分割成独立的、可复用的组成部分。只需要专注于构建每个单独的部分。比如按钮,对话框,列表,输入框都是组件。

    • 组件可以接受参数(props),可以返回一个在页面上展示的React元素

    函数定义组件(无状态)

    无状态组件:一般用于简单的页面展示

    // 用函数定义了名为Hello组件
    function Hello(props) {
        return <h1>Hello {props.name} !</h1>;
    }
    
    // react进行元素渲染
    ReactDOM.render(
        <Hello name="itheima props"/>,
        document.getElementById('root')
    );
    

    类定义组件(有状态)*

    • class 必须要ES6支持

    有状态组件:可以维护自己的状态State信息,完成更加复杂的显示逻辑

    // 用类定义 名为Hello组件
    class Hello extends React.Component {
        render(){
            return <h1>Hello {this.props.name} !</h1>;
        }
    }
    
    // react进行元素渲染
    ReactDOM.render(
        <Hello name="itheima class"/>,
        document.getElementById('root')
    );
    
    • 以上两种组件效果在React相同

    类定义组件名称必须是大写

    建议在return元素时,用小括号()包裹

    组合组件

    • 组件之间可以相互引用,通常把App作为根组件

      // 用类定义 名为Hello组件
      class Hello extends React.Component {
          render() {
              return <h1>Hello {this.props.name} !</h1>;
          }
      }
      // 根组件
      function App(props) {
          return (
              <div>
                  <div>
                      <h2>团队名称: {props.team}</h2>
                      <p>成员个数: {props.count}</p>
                      <p>成立时间: {props.date.toLocaleString()}</p>
                  </div>
                  
                  <Hello name="悟空" />
                  <Hello name="八戒" />
                  <Hello name="沙僧" />
                  <Hello name="三藏" />
              </div>
          );
      }
      // react进行元素渲染
      ReactDOM.render(
          <App team="西天取经团" count={4} date={new Date()}/>,
          document.getElementById('root')
      );
      

    • 注意:组件的返回值只能有一个根元素,所以用一个div包裹所有Hello元素

    • 在google插件市场搜索安装React查看DOM结构

    Props属性*

    • props有两种输入方式:
      • 引号"" :输入字符串值,
      • 大括号{} :输入JavaScript表达式,大括号外不要再添加引号。
    • props的值不可修改,属性只读,强行修改报错
    • 类定义组件中使用props需要在前边加 this.

    State状态*

    • 自动更新的时钟

      class Clock extends Component {
          render(){
              return (
                  <div>
                      <h1>当前时间:</h1>
                      <h3>current: {new Date().toLocaleString()}</h3>
                  </div>
              );
          }
      }
      
      setInterval(() => {
          ReactDOM.render(
              <Clock />,
              document.getElementById('root')
          );
      }, 1000);
      

      应用一般执行一次ReactDOM.reader() 渲染

      在组件内部进行更新, 每个时钟内部都维护一个独立的date信息

    • 在组件内部使用局部state状态属性

      class Clock extends Component {
      
          constructor(props) {
              super(props);
              // state定义:在constructor构造函数进行state状态的初始化
              this.state = {
                  title: "时钟标题",
                  date: new Date()
              };
              
              setInterval(() => {
                  this.tick();
              }, 1000);
          }
      
          tick(){
              // 更新date, 数据驱动, 必须通过setState函数修改数据并更新ui
              this.setState({
                  date: new Date()
              })
          }
      
          render(){
              return (
                  <div>
                      <h1>{this.state.title}</h1>
                      <h3>current: {this.state.date.toLocaleString()}</h3>
                  </div>
              );
          }
      }
      
      ReactDOM.render(
          <Clock />,
          document.getElementById('root')
      );
      
    • state特性:

      1. state 一般在构造函数初始化。this.state={...}
      2. state可以修改,必须通过this.setState({...})更新并渲染组件
      3. 调用setState更新状态时,React最自动将最新的state合并到当前state中。

    组件生命周期

    React中组件的生命周期

    • 生命周期常用的函数

      componentDidMount:组件已挂载, 进行一些初始化操作

      componentWillUnmount: 组件将要卸载,进行回收操作,清理任务

    事件处理

    定义组件事件

    class App extends Component {
    
        handleClick(e){
            console.log("handleClick!")
            console.log(this);
        }
    
        render(){
            return (
                <div>
                    <button onClick={() => this.handleClick()}>
                        按钮:{'{() => this.handleClick()}'}
                    </button>
                </div>
            );
        }
    }
    

    属性初始化器语法*

    // 属性初始化器语法 (Property initializer syntax)
    handleClick = () => {
        console.log("handleClick!")
        console.log(this);
    }
    

    参数传递*

    class App extends Component {
        handleClick(e, str, date){ // 参数要和调用者传入的一一对应
            console.log(this)
            console.log(e)
            console.log(str, date)
        }
        render(){
            return (
                <button onClick={(e)=>this.handleClick(e, "参数" , new Date())}>
                    按钮1:{'箭头函数'}
                </button>
            );
        }
    }
    

    参数要和调用者传入的一一对应

    计数器游戏

    import React, { Component } from 'react';
    import ReactDOM from 'react-dom';
    
    // 类定义组件的写法
    class App extends Component {
        constructor(props) {
            super(props);
            // 绑定this到事件函数
            this.countPlus = this.countPlus.bind(this);
            this.state = { 
                count: 0,
                timeSurplus: 10
             };
        }
    
        // 组件已挂载, 开启周期任务
        componentDidMount() {
            this.timerId = setInterval(() => {
    
                this.setState((preState) => ({
                    timeSurplus: preState.timeSurplus - 1
                }))
    
                // 在合适的时候, 结束周期函数
                if(this.state.timeSurplus <= 0){
                    clearInterval(this.timerId)
                }
    
            }, 1000);
        }
    
        countPlus(){
            // 更新当前count数字.
            console.log(this)
    
            // 如果时间到了, 返回
            if (this.state.timeSurplus <= 0){
                return;
            }
    
            // 更新数据会自动触发UI的重新render
            // this.setState({
            //     count: this.state.count + 1
            // })
            // 通过之前state状态更新现在的状态
            this.setState((preState) => ({
                count: preState.count + 1
            }))
        }
    
        render() {
            return (
                <div>
                    <h1>{this.props.title}</h1>
                    <h2>
                        {
                            this.state.timeSurplus <= 0 ? 
                            ("时间到, 总数" + this.state.count) : 
                            ("剩余时间:" + this.state.timeSurplus)
                        }
                        
                    </h2>
                    <button onClick={this.countPlus}>
                        计数: {this.state.count}
                    </button>
                </div>
            );
        }
    }
    
    ReactDOM.render(
        <App title="计数器, 试试你的手速!"/>,
        document.getElementById('root')
    );
    

    style样式(JSX写法)

    1. 直接写在style属性中

      <button style={{ 200, height: 200}}>我是按钮</button>
      
    2. 通关变量声明样式并引用

      const btnStyle = {  200, height: 200 };
      ...
      <button style={btnStyle} onClick={this.handleClick}>我是按钮</button>
      

  • 相关阅读:
    VSCode settings.json的配置样例
    用css让div高度自动撑满屏幕
    C# 后端接受前端上传的文件
    netcode 控制台项目生成exe文件
    C# UDP发送和接收
    C# 直播录制视频
    Vs2017 FrameWork EF Mysql Mvc 三层整合1
    Vs2017 FrameWork EF Mysql 控制台应用
    Vs2017 NetCode EF Mysql 控制台应用
    Vs2017 NetCode Mvc EF Mysql 整合2
  • 原文地址:https://www.cnblogs.com/xiaocongcong888/p/9436171.html
Copyright © 2020-2023  润新知