React的contextType的使用方法简介

上一篇介绍了Context的使用方法。但是Context会让组件变得不纯粹,因为依赖了全局变量。所以这决定了Context一般不会大规模的使用。所以一般在一个组件中使用一个Context就好。

由于Consumer的特性,里面的代码必须是这个函数的返回值。这样就显得复杂与不优雅了。那该怎么解决呢?这样contextType就派上用场了。
 

还拿上一篇的demo来举例。并且修改它。 上一篇的代码:

import React, { Component, createContext } from 'react';

const BatteryContext = createContext();

//声明一个孙组件
class Leaf extends Component {
  render() {
    return (
      
        {
          battery => 

Battery : {battery}

}
) } } //声明一个子组件 class Middle extends Component { render() { return } } class App extends Component { render(){ return ( ); } } export default App;

 

 接下里我们修改他,使他更加优雅一些:

我们只需要修组件的代码就可以。

 

首先我们用static来声明contextType:

static contextType = BatteryContext;

 

 

这样在运行时就可以获取到一个新的属性。我们来接收他。
const battery = this.context;

 

这样Consumer就可以完全不再使用了。
 return

Battery : {battery}


 

 全部代码:

import React, { Component, createContext } from 'react';

const BatteryContext = createContext();

//声明一个孙组件
class Leaf extends Component {
  static contextType = BatteryContext;
  render() {
    const battery = this.context;
    return

Battery : {battery}

} } //声明一个子组件 class Middle extends Component { render() { return } } class App extends Component { state = { battery: 60, } render() { const { battery } = this.state; return ( <button type="button" onClick={() => this.setState({ battery: battery - 1 })} > 减减 ); } } export default App;

 

 

效果图:

React的contextType的使用方法简介_第1张图片

 

效果和使用Consumer没有什么区别。可见只有一个Context的时候,使用contextType要比使用Consumer简单的多。

 

你可能感兴趣的:(React的contextType的使用方法简介)