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

React扩展:fragment、Context

目录

1.fragment

fragment标签能包裹其它标签,但最后不会渲染到DOM树上。

import React, { Component, Fragment } from 'react'

export default class Demo extends Component {
  render() {
    return (
      <Fragment>
        <input type="text" />
        <input type="text" />
      </Fragment>
    )
  }
}

通常来说,render函数返回的东西需要用<div></div>包裹。用fragment标签包裹,最后fragment也不会被渲染,相较于前者,能少一对<div></div>。

2.Context

父子组件间通信用props就行,祖组件后代组件之间(间隔不止一代)通信用Context
应用开发中一般不用Context,一般都用它封装React插件。

/src/components/Demo/index.jsx

import React, { Component } from 'react'
import './index.css'

// 创建Context对象
const MyContext = React.createContext();
const {Provider,Consumer} = MyContext
export default class A extends Component {

  state = {username:'tom'}

  render() {
    const {username} = this.state
    return (
      <div className='parent'>
        <div>A组件</div>
        <div>用户名:{username}</div>
        <Provider value={username}>
          <B />
        </Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className='child'>
        <div>B组件</div>
        <C />
      </div>
    )
  }
}

/*
// 类式组件
class C extends Component {
  // 声明接收context
  static contextType = MyContext
  render() {
    return (
      <div className='grandchild'>
        <div>C组件</div>
        <div>从A组件接收到的用户名:{this.context}</div>
      </div>
    )
  }
}
*/

// 函数式组件
function C() {
  return (
    <div className='grandchild'>
      <div>C组件</div>
      <div>从A组件接收到的用户名:
        <Consumer>
          { value =>  `${value}` }
        </Consumer>
      </div>
    </div>
  )
}

/src/components/Demo/index.css

.parent{
  width: 500px;
  background-color: orange;
  padding: 5px;  
}

.child{
  width: 400px;
  background-color: skyblue;
  padding: 5px;
}

.grandchild{
  width: 300px;
  background-color: red;
  padding: 5px;
}

3.组件优化PureComponent

问题:只有当组件的state或props数据发生改变时,才重新render()。
原因:组件中的shouldComponentUpdate()总是返回true
解决:
①重写shouldComponentUpdate()方法,比较新旧state或props数据,有变化返回true,没有返回false
②使用PureComponent,PureComponent重写了shouldComponentUpdate(),只有state或props有变化才返回true,项目中一般使用PureComponent来优化。

4.

相关文章:

  • InnoDB详解2
  • 软件需求说明书(GB856T——88)基于协同的在线表格forture-sheet
  • 动态规划——线性dp
  • python10_IO目录处理
  • PostgreSQL实用技巧
  • Linux tracepoint 简介
  • java 瑞吉外卖day6 移动端 套餐 菜品展示 购物车加减,清空
  • Debezium系列之:打通Debezium2.0以上版本的使用技术
  • String类及常用方法
  • Rasa 基于知识库的问答 音乐百科机器人
  • 内科大深度学习期末复习笔记
  • 搭建nacos
  • Java面试--AQS
  • 电脑重装系统win11如何更改默认下载路径
  • MTI运动传感器ROS配置
  • DFS——剪枝优化迭代加深
  • 【Flutter】packages思维以及使用Java添加Android平台特定的实现在Flutter框架里的体现和运用
  • 无向图以及图的java代码实现
  • 大数据平台之Hadoop复习详细知识点
  • 四、网络层(五)IP组播