当前位置: 首页 > news >正文

【react】语法总结

【react】基础语法总结

1.创建react
creat-react-app 文件名
cd 文件名
npm install(下载依赖)
npm start

//一个组件新建一个文件夹

2.react文件夹
//APP.js文件
//引入React
import React,{Component} from 'react;
//引入组件
//第一步:
import List01 from "../Component/list01/list01"

    //声明小组件的方法:
    1.以函数的方式声明小组件
    function Table(){
    return(
        <h2>
            函数小组件
        </h2>
    )
    }
    2.以类的方式声明大组件
    class Nav extends Component{
        render(){
            return(
                <div className="Nav">
                类声明的小组件
                </div>
            )
        }
    }
    3.以变量或者常量的形式声明小组件
    const el = <h1>直接创建小组件</h1>

    //小组件  ==>  函数
    //大组件  ==>  类

//jsx语法:
export default class App extends React.Component{
    render(){
        return(
            <div className="App">
                {/*  注释,引入函数方式声明的组件  */}
               <Tbale/>
               {/*  注释,引入类方式声明的组件  */}
               <Nav/>
               {/*  注释,渲染变量或者常量创建的方式声明的组件  */}
               {el}

               //引入组件
               //第二步:
               <List01/>
               <List02/>
               <List03/>
               <List04/>
               <List05/>
            </div>
        )
    }
}


3.list01组件
import React,{Component} from 'react';
//导入List02
import List02  from "../Component/list02/导入List02"

//函数组件:1.props   2.解构赋值的方式
//1.函数小组件
function Message(props){
    return(
        <ul>
           //接收数组
           <li>{props.arr[0]}</li>
           <li>{props.arr[1}</li>
           <li>{props.arr[2]}</li>
        </ul>
    )
}

//2.解构赋值的方式
//解构赋值  (形参解构实参)
function Message(arr,name){  //形参
    return(
        <ul>
           //接收数组
           <li>{arr[0]}</li>  //形参
           <li>{arr[1}</li>
           <li>{arr[2]}</li> 
           //渲染name
           <li>{name}</li> 
        </ul>
    )
}

//导入主组件
exprot default class List01 extends Component{
    render(){
        //组件内部声明的数据
        const list = {
            title:'商品',
            num:2323,
            price:'$123'
        }

        return(
            <div className="List01">
               //1.传参,数组
               <Message arr={["苹果","香蕉","葡萄"}/>

               //2.传参,数组  (形参解构实参)
               <Message 
                    arr={["苹果","香蕉","葡萄"}   //数组
                    name="tom"                   //其他内容
                    obj={{title:'rewr}}          //对象
               /> //实参


               //导入List02
               <List02  {...list}/>  //扩展运算符


            </div>
        )
    }
}

4.list02组件
import React,{Component} from 'react';
//导入主组件
exprot default class List02 extends Component{
    render(){

        //打印传递的数据
        //this.props 是从Component里继承(如果是函数就没办法用this.props继承)
        console.log(this.props);

        //2.用解构赋值接收
        const {title,num,price} = this.props;

        return(
            <div className="List02">
              //1.用普通的方法接收接收List01里的数据
              {this.props.title}---
              {this.props.num}---
              {this.props.price}

              //2.用解构赋值的方式,接收List01里的数据
              {title}---{num}---{price}
            </div>
        )
    }
}



5.list03组件
import React,{Component} from 'react';

//CSS in js 库
//耦合(低耦合高复用):代码之间相互影响的概率很低,单独可以用作其他,代码的复用率很高
npm i styled-components -S

//数据
const a = '哈哈哈哈嗝';
//函数
function fn1(x){
  return x;
}

//导入主组件
exprot default class List03 extends Component{
    render(){
        return(
            <div className="List03">
              <ul>
                  <li>{ a }</li>
                  <li>{ fn1(10) }</li>
                  <li>{ 1 < 3 ? '哈哈哈':'嘿嘿嘿' }</li>
                  {
                      3 > 2 ?(
                          <h1>为true</h1>
                      ):(
                        <h1>为false</h1>
                      )
                  }
              </ul>
            </div>
        )
    }
}



6.list04组件
import React,{Component} from 'react';

const list = {
    title:'蛋糕',
    price:123
}

//导入主组件
exprot default class List04 extends Component{
    //props接收传参
    constructor(props){  //继承component类中的内容
        //在构造函数里表示父类的构造函数
        //在原型方法中是个对象
        super(props);
        //声明当前组件的动态数据
        //state的赋值,必须在类组件的构造函数中
        this.state = {
            name:"Rose",
            sex:'女',
            count:0
        }
    }
    render(){
        //const {} = this.props
        return(
            <div className="List04">
               {list.title} --- {list.price}
               <h1>{this.state.name}</h1>
               <h1>{this.state.sex}</h1>

               <h2>必须渲染数字 {this.props.num}</h2>  //666

               <h2>{this.state.count}</h2>
               <button οnclick={()=>{  //箭头函数
                   //错误:this.state.count+=10;
                  this.setState({
                      count:this.state.count++;
                  })
               }></button>
            </div>
        )
    }
}

//提前设置默认参数
List05.defaultProps = {
    num:666
}


7.list05组件
import React,{Component} from 'react';

//导入主组件
exprot default class List05 extends Component{
    state={
        flag:true,
    }
    render(){
        return(
            <div className="List05">
               {
                   //分支渲染 写法1
                   (()=>{   //箭头函数
                       if(this.state.flag){
                          return <h2>我是true</h2>
                       }else{
                          return <h2>我是false</h2>
                       }
                   })()
               }

               {
                 //分支渲染 2
                  function(_this){   //形参
                    if(_this.state.flag){
                        return <h2>我是true</h2>
                     }else{
                        return <h2>我是false</h2>
                     }
                  }(this)  //实参
               }

               {
                    function(){
                        //分支渲染 3
                        return this.state.flag ? (<h2>我是true</h2>) : (<h2>我是false</h2>)
                        }
               }

               {
                   function(){
                    //分支渲染 4
                    return this.state.flag ? (<h2>我是true</h2>) : (<h2>我是false</h2>)
                   }.bind(this)()  
                    //.bind相当于将这个函数复制了一遍,最后的()是调用这个整个函数的意思,相当于链式操作
                }

                {
                    //分支渲染 5
                    this.state.flag && <h2>我是true</h2>
                }

                {
                    //分支渲染 6
                    this.state.flag && (()=>{
                        return <h2>哈哈哈哈嗝</h2>
                    })()
                }
            </div>
        )
    }
}

8.list06组件
import React,{Component} from 'react';

const goodList = [
    {
    id:1,
    name:'蛋糕',
    price:'¥89.9'
    },
    {
    id:2,
    name:'酸奶',
    price:'¥89.9'
    },
    {
    id:3,
    name:'鸭脖',
    price:'¥19.9'
    }
]
<!-- 循环创建元素 -->
const elList  = list.map((item,i)=>{
  return(
    <ul key={i}>
        <li>{item.id}</li>
        <li>{item.name}</li>
        <li>{item.price}</li>
    </ul>
  )
})


//导入主组件
exprot default class List06 extends Component{
    state={
        goodList:[
          {
             id:1,
             name:'蛋糕',
             price:'¥89.9'
          },
          {
            id:2,
            name:'酸奶',
            price:'¥89.9'
         },
         {
            id:3,
            name:'鸭脖',
            price:'¥19.9'
         }
        ]
    }
    render(){
        return(
            <div className="List05">
               <h1>----------循环</h1>
               {
                   <!-- 自执行函数 -->
                   (()=>{
                       return this.state.goddList.map((item,index)=>{
                           console.log(item)
                        return(
                            <ul key={index}>
                                <li>{item.id}</li>
                                <li>{item.name}</li>
                                <li>{item.price}</li>
                            </ul>
                        )
                       })
                   })()
               }

               <!-- 调用外部的循环 -->
               {elList}
            </div>
        )
    }
}


9.list07组件
import React,{Component} from 'react';

<!-- 外部声明函数 -->
function fn(){
    let newCount = this.state.count;
    this.setState({
        count:newCount+=2
    })
}


//错误示范:
const fn1 = () => {
    let newCount = this.state.count;
    this.setState({
        count:newCount+=3
    })
}



exprot default class List07 extends Component{
    constructor(props){
        super(props)
        this.state={
            count:0
        }
        this.fn4 = this.fn4.bind(this); //修改了fn4的指向
    }
    <!-- 类的原型函数 -->
    fn3(){
        <!-- react组件类的原型函数中,this=>undefined -->
        console.log(this);  //undefinened
        let newCount = this.state.count;
        this.setState({
            count:newCount+=3
        })
    }

    fn4() {
        let newCount = this.state.count;
        this.setState({
            count:newCount+=4
        })
    }

    <!-- fn5即是一个属性又是一个函数,能够保留this指向 -->
    fn5 = () => {
        let newCount = this.state.count;
        this.setState({
            count:newCount+=5
        })
    }
    
    render(){
        return(
            <div className="List07">
                <h1>{this.state.count}</h1>
                <!-- 方法一:将函数直接绑定到按钮上 -->
                <button onclick="{()=>{
                    let newCount = this.state.count;
                    this.setState({
                        count:newCount++
                    })
                }}" >按钮1</button>
             
                <!-- 不加.bind会报错,加上之后将this传递过去 -->
                <button onclick="{fn.bind(this)}">按钮2</button>

                <!-- 错误方式 -->
                <!-- <button οnclick="{fn1.bind(this)}">按钮2</button> -->

                <button onclick="{this.fn3.bind(this)}">按钮3</button>

                <button onclick="{this.fn4.bind(this)}">按钮4</button>

                <button onclick="{this.fn4.bind(this)}">按钮5</button>
            </div>
        )
    }
}




9.list08文件夹下的两个文件(PropTypes进行类检查)
import React,{Component} from 'react';

<!-- react 提供类型检查 -->
<!-- import PropTypes from 'prop-types'; -->

<!-- 操作DOM结构
    ref:为组件提供访问DOM的方法或者调用其他子组件的方法,
         万步得已,不建议使用!!!
 -->

exprot default class Home extends Component{
    inpRef = React.createRef();   //类的属性
    navRef = React.createRef();

    render(){
        return(
            <div className="Home">
                 <input type="text" ref={this.inpRef}/>
                 <!-- 点击按钮获取焦点 -->
                 <button 
                    onClick={()=>{
                     console.log(this.inpRef)
                     this.inpRef.current.focus();
                     }}
                  >获取焦点</button>  //操作DOM元素

                 <Nav/>

                 <button
                   οnclick={()=>{
                       console.log(this.navRef);
                   }}
                 >获取子组件</button>
            </div>
        )
    }
}

<!-- 进行类型检查 -->
<!-- Home.PropTypes = {
    name:PropTypes.string
} -->



import React,{Component} from 'react';

exprot default class Nav extends Component{
    render(){
        return(
            <div className="Nav">
                 <ul>
                     <li>2</li>
                     <li>4</li>
                     <li>6</li>
                 </ul>
            </div>
        )
    }
}

10.导入路由
<!-- content页面 -->
import React,{Component} from 'react';

<!-- 导入路由需要的组件 -->
import {BrowsRouter,Route,Link} from "react-router-dom"
<!-- 引入路由对应的组件 -->
import List from './list'
import Order from './order'

exprot default class Content extends Component{
    render(){
        return(
            <div className="Content">
                <!-- 将list 和 order 作为路由导入 -->
                 <BrowsRouter>
                   <ul>
                       <link>
                           <Link to="/list">列表</Link>
                       </li>
                       <li>
                           <Link to="/order">订单</Link> 
                       </li>
                   </ul>

                   <Route path="/list" component={List}></Route>
                   <Route path="/order" component={Order}></Route>


                 </BrowsRouter>
            </div>
        )
    }
}


<!-- 订单 -->
import React,{Component} from 'react';

exprot default class Order extends Component{
    render(){
        return(
            <div className="Order">
               订单
            </div>
        )
    }
}

<!-- 列表 -->
import React,{Component} from 'react';

exprot default class List extends Component{
    render(){
        return(
            <div className="List">
                列表
            </div>
        )
    }
}


11.
import React,{Component} from 'react';
<!-- 引入根组件 -->
import Content from './components/router-demo/content';
import {BrowsRouter} from "react-router-dom";
<!-- 在content的文件中不用再次引入了 -->

exprot default class APP extends Component{
    render(){
        return(
            <div className="APP">
                <BrowserRouter>  
                  <Content/>
                </BrowserRouter>
            </div>
        )
    }
}


12.传值和接收参数
import React,{Component} from 'react';
import {Redirect} from "react-router-dom";

exprot default class List extends Component{
    render(){
        return(
            <div className="List">
                <ul>
                    <li>
                        <Link to="/list/list01">列表一</Link>
                    </li>
                    <!--1. 需要在Route设置参数   '/:参数名',   参数会暴露在URL中,参数不会丢失 -->
                    <li>
                        <Link to="/list/list02/Rose">列表二</Link> //拼接ROSe
                    </li>
                    <!-- 2.query传参:   参数不会暴露在URL中,并且刷新数据会丢失掉 -->
                    <li>
                        <Link to={{
                            pathname:"/list/list02",
                            query:{
                                hobby:'打篮球'
                            }
                        }}>列表二query传参</Link>
                    </li>

                     <!-- 3.state传参:  参数不会暴露在URL中,并且刷新数据会丢失掉 -->
                     <li>
                        <Link to={{
                            pathname:"/list/list02",
                            state:{
                                sex:'女'
                            }
                        }}>列表二state传参</Link>
                    </li>

                      <!-- 4.search传参:  参数不会暴露在URL中,并且刷新数据会丢失掉 -->
                      <li>
                        <Link to={{
                            pathname:"/list/list02",
                            search:"id=123&details=衣物"
                        }}>列表二search传参</Link>
                    </li>
                </ul>
                 
                <!-- 第二种默认的路由配置:默认路由配置 不展示url完整路径-->
                <!-- exact属性 -->
                <Route path="/list" exact component={List02}></Route>
                <Route path="/list/list01" component={List01}></Route>

                <!-- 1.传参 -->
                <Route path="/list/list02/:name" component={List02}></Route>
                <!-- 2.query传参 -->
                <Route path="/list/list02" component={List02}></Route>
                 <!-- 3.state传参 -->
                 <Route path="/list/list02" component={List02}></Route>
                  <!-- 4.search传参 -->
                <Route path="/list/list02" component={List02}></Route>

                <!-- 路由重定:跳到二级页面优先展示那个页面 ,展示url完整路径-->
                <Redirect to="/list/list02/>
            </div>
        )
    }
}


import React,{Component} from 'react';

exprot default class List02 extends Component{
    render(){
        console.log(this.props);  //打印一下传递的参数

        <!-- 解构 :相当于:this.props.match.params.name-->
        const {
            match:{params:{name}},  //1.传参,
            location:{query:{hobby}}  //2.query传参
            location:{state:{sex}}   //3.state传参
            location:{search}   //4.search传参
        } = this.props;

        return(
            <div className="List02">
                 <!-- 取值 -->
                 <p>{name}</p>
                 <p>{hobby}</p>
                 <p>{sex}</p>   //接收参数
                 <p>{search}</p>
            </div>
        )
    }
}



<!-- 13.404页面 -->
import React,{Component} from 'react';
import NorFound from './notFound'

exprot default class content extends Component{
    render(){
        return(
            <div className="content">

                <!-- Switch 将Route变成互斥组件 -->
                <Switch>
                    <!-- 路由配置 -->
                   <Route component={NotFound}/>
                </Switch>

               
            </div>
        )
    }
}





import React,{Component} from 'react';

exprot default class notFound extends Component{
    render(){
        return(
            <div className="notFound">
                
            </div>
        )
    }
}

相关文章:

  • 【React】语法
  • Web前端工程师面试-HTML
  • Javascript Date对象
  • 谷歌浏览器使用记住密码功能后的input背景
  • jQuery为多元素添加统一样式
  • js 判断字符串中是否包含某个字符串
  • js 将两个对象合并成一个对象
  • 修改input的type属性
  • js查找字符串中某个字符出现的位置及次数
  • 2021-07-16 element-ui Radio-group 默认不回显问题
  • 2021-07-20 div超出省略2种方式
  • 2021-07-28 el-table-column里面的内容只显示一行
  • 页面置顶效果
  • 2021-08-26 js合并两个对象
  • 2021-08-26 el-table-column里面的内容只显示一行
  • [译] React v16.8: 含有Hooks的版本
  • 【RocksDB】TransactionDB源码分析
  • 【刷算法】从上往下打印二叉树
  • 【跃迁之路】【477天】刻意练习系列236(2018.05.28)
  • Android路由框架AnnoRouter:使用Java接口来定义路由跳转
  • HTTP那些事
  • MD5加密原理解析及OC版原理实现
  • Netty 框架总结「ChannelHandler 及 EventLoop」
  • OpenStack安装流程(juno版)- 添加网络服务(neutron)- controller节点
  • Python 基础起步 (十) 什么叫函数?
  • React-flux杂记
  • Redis 懒删除(lazy free)简史
  • SpiderData 2019年2月13日 DApp数据排行榜
  • spring-boot List转Page
  • 对超线程几个不同角度的解释
  • 高性能JavaScript阅读简记(三)
  • 给Prometheus造假数据的方法
  • 前端代码风格自动化系列(二)之Commitlint
  • mysql面试题分组并合并列
  • Redis4.x新特性 -- 萌萌的MEMORY DOCTOR
  • Salesforce和SAP Netweaver里数据库表的元数据设计
  • 曜石科技宣布获得千万级天使轮投资,全方面布局电竞产业链 ...
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • !!【OpenCV学习】计算两幅图像的重叠区域
  • (day 2)JavaScript学习笔记(基础之变量、常量和注释)
  • (二十五)admin-boot项目之集成消息队列Rabbitmq
  • (附源码)python旅游推荐系统 毕业设计 250623
  • (附源码)springboot青少年公共卫生教育平台 毕业设计 643214
  • (一)u-boot-nand.bin的下载
  • (转)Mysql的优化设置
  • (转)shell中括号的特殊用法 linux if多条件判断
  • * CIL library *(* CIL module *) : error LNK2005: _DllMain@12 already defined in mfcs120u.lib(dllmodu
  • .mysql secret在哪_MYSQL基本操作(上)
  • .NET 中 GetHashCode 的哈希值有多大概率会相同(哈希碰撞)
  • .NET 中各种混淆(Obfuscation)的含义、原理、实际效果和不同级别的差异(使用 SmartAssembly)
  • .NET开源项目介绍及资源推荐:数据持久层 (微软MVP写作)
  • .Net中的集合
  • .one4-V-XXXXXXXX勒索病毒数据怎么处理|数据解密恢复
  • .pings勒索病毒的威胁:如何应对.pings勒索病毒的突袭?
  • /bin/bash^M: bad interpreter: No such file or directory