React-Native优化之PureComponent

本文对比了React中Component与PureComponent的区别,PureComponent通过浅比较优化shouldComponentUpdate方法,减少不必要的渲染,适用于不变的组件。并通过示例展示了如何在特定情况下使PureComponent重新渲染。

React15.3的发布中包含了PureComponent,这个类最重要的用法是为了优化React的性能,下面我们将看下它是如何优化的。

Component VS PureComponent

首先要看Component的生命周期:

当props或者state改变的时候,会执行shouldComponentUpdate方法来判断是否需要重新render组建,我们平时在做页面的性能优化的时候,往往也是通过这一步来判断的。Component默认的shouldComponentUpdate返回的是true,如下:

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

而PureComponent的shouldComponentUpdate是这样的:

if (this._compositeType === CompositeTypes.PureClass) {
  shouldUpdate = !shallowEqual(prevProps, nextProps) || ! shallowEqual(inst.state, nextState);
}

这里的比较,只会做潜比较,即比较两者的内存地址是否相同,而对于其值是否发生变化,则不会理会。我们通过以下的例子来看下:

例子

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { PureComponent,Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Button
} from 'react-native';

export default class test extends PureComponent {
  constructor(props){
    super(props);
    this.state = {
       number : 1,
       numbers: [],
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <Button title={'number + 1'} onPress={this.numberAdd.bind(this)} />
        <Text>number value: {this.state.number}</Text>
        <Button title={'numbers + 1'} onPress={this.numbersAdd.bind(this)} />
        <Text>numbers length: {this.state.numbers.length}</Text>
      </View>
    );
  }

  numberAdd(){
      this.setState({number: ++this.state.number });
  }


  numbersAdd(){
    let numbers = this.state.numbers;
    numbers.push(1);
    this.setState({numbers: numbers});
    console.log(this.state.numbers);
  }


}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('test', () => test);

界面如下:

这里去点击number+1 和 numbers+1都不会有任何页面的变化。

如何让PureComponent重绘

那如果PureComponent变化的时候(这其实不符合我们的初衷),我们要怎么做呢?这里有两个办法:

  1. 重写shouldUpdateComponent方法
  2. props或者state增减参数

代码如下:

numbersAdd(){
    let numbers = this.state.numbers;
    numbers.push(1);
    this.setState({numbers: numbers});
    console.log(this.state.numbers);

    this.setState({newState: 1});
  }

这样,shouldComponentUpdate的返回值也会是true。

总结

综上,PureComponent非常适合于不变的组件,尤其是和数据、业务无关的纯展示组件,因为它的节省了大量比较的工作。但是对于大部分的业务来说,界面很少会有不变的组件,所以使用的场景会比较少,但是如果遇到,请尽情使用!

<think>好的,用户想查找关于react-native-markdown-display库的使用或信息。首先,我需要确认这个库的基本情况,比如它的功能、安装方法、基本用法等。用户可能需要快速上手的信息,所以应该先介绍如何安装,然后展示一个简单的示例代码。 接下来,用户可能关心如何自定义样式。因为不同的应用可能需要不同的Markdown渲染样式,所以需要说明如何通过props传递自定义样式对象,并给出示例,比如修改标题颜色或代码块背景色。 然后,处理自定义渲染组件也是一个常见需求。用户可能希望替换默认的渲染组件,比如将图片换成自定义的组件。这里需要提到如何使用renderRules属性,并给出代码示例。 事件处理也是重要的部分,比如链接点击。用户可能需要知道如何拦截链接点击事件,并执行自定义操作,比如应用内跳转而不是打开浏览器。这里需要说明onLinkPress属性的用法。 兼容性方面,用户可能会遇到与其他库的冲突,特别是react-native-markdown-package。需要提醒用户注意库的命名冲突,并提供解决方案,比如卸载冲突的库或使用别名。 性能优化方面,长文档的渲染可能影响应用性能。应该建议使用PureComponentReact.memo来优化子组件,或者分块渲染。 最后,提供官方文档链接和社区资源,方便用户进一步查阅。同时,根据常见问题生成相关问题,帮助用户深入探索。 需要检查是否有遗漏的部分,比如版本兼容性、常见错误处理,或者与其他库的集成问题。但根据现有信息,以上内容应该覆盖了用户的主要需求。确保所有代码示例正确,使用正确的语法,并引用相关资源。</think>### react-native-markdown-display 使用指南 react-native-markdown-display 是一个专门为 React Native 设计的 Markdown 渲染库,支持 160+ CommonMark 特性,采用高度优化的渲染方案[^1]。 #### 1. 基础安装 ```bash yarn add react-native-markdown-display # 或 npm install react-native-markdown-display ``` #### 2. 基础用法 ```javascript import Markdown from 'react-native-markdown-display'; const App = () => ( <Markdown> # 标题 - 列表项 **加粗文本** [链接](https://example.com) </Markdown> ); ``` #### 3. 样式自定义 通过`style`属性实现细粒度样式控制: ```javascript const markdownStyles = { heading1: { color: '#ff0000', fontSize: 24, }, code_block: { backgroundColor: '#f5f5f5', borderWidth: 1, } }; <Markdown style={markdownStyles}>{content}</Markdown> ``` #### 4. 自定义渲染组件 使用`renderRules`覆盖默认渲染逻辑: ```javascript const customRules = { image: (node, children, parent, styles) => ( <MyCustomImageComponent src={node.attributes.src} /> ) }; <Markdown rules={customRules}>{content}</Markdown> ``` #### 5. 事件处理 拦截链接点击事件: ```javascript const handleLinkPress = (url) => { // 执行应用内导航 return false; // 阻止默认浏览器打开 }; <Markdown onLinkPress={handleLinkPress}>{content}</Markdown> ``` #### 6. 兼容性注意 与 react-native-markdown-package 存在命名冲突时: ```bash # 建议解决方案 npm uninstall react-native-markdown-package # 或使用别名导入 import MarkdownDisplay as Markdown from 'react-native-markdown-display'; ``` #### 7. 性能优化 对于长文档建议: ```javascript // 使用PureComponent优化子组件 class OptimizedComponent extends React.PureComponent { render() { return <Markdown>{largeContent}</Markdown>; } } // 或使用分块渲染 <ScrollView> {chunks.map((chunk, i) => ( <Markdown key={i}>{chunk}</Markdown> ))} </ScrollView> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值