zoukankan      html  css  js  c++  java
  • react中使用decorator 封装context

    2020-03-27
    react中使用decorator 封装context

    在传统的react context中,子组件使用context十分繁琐,如果需要使用context的子组件多的话

    每个组件都需要写consumer,所有如果能使用decorator的话,就会方便很多

    对比一下下:
    方案1: 传统的context
    每一个需要使用context的组件都需要写consumer
     
    import React from 'react';
    import MyContext from '../context.js';
    
    class Son extends React.Component {
      render() {
        return (
          // 每一个需要使用context的组件 你都需要用consumer包装一下
          // 如果有一百个呢???? 而且写法复杂很不友好!
          <MyContext.Consumer> 
            {value => (
              <div>
                <div>{value.name}</div>
                <div>{value.age}</div>
              </div>
            )}
          </MyContext.Consumer>
        )
      }
    }
    
    export default Son;
    方案2: 牛p的decorator
    哪个组件要用 装饰一下即可
    import React from 'react';
    import MyContext from '../context.js';
    
    function withUser(Component) { // 定义一个方法,这个方法就是decorator装饰器
      return class extends React.Component{ // 方法返回了一个组件 是将原组件装饰之后的组件
        render() {
          return (
            // 装饰器统一将原组件用Consumer包装起来 并将context的value值存在组件props的指定key中,这里是user
            <MyContext.Consumer> 
              {value => <Component user={value} {...this.props} />}
            </MyContext.Consumer>
          )
        }
      }
    }
    
    export default withUser;
     
    import React from 'react';
    import withUser from './decorator';
    
    @withUser // 装饰器的参数默认就是下面的组件了
    class Son extends React.Component {
      render() {
        return (
          <div>
            {/* 经过 装饰器装饰过的组件中 props中已经有了context的值了, key是user */}
            <div>{this.props.user.name}</div> 
            <div>{this.props.user.age}</div>
          </div>
        )
      }
    }
    
    export default Son;
  • 相关阅读:
    javascript创建对象的方法--基本模式
    javascript进阶课程--第二章--对象
    JavaScript中的global对象,window对象以及document对象的区别和联系
    onblur 对象失去焦点事件
    php排序
    php数组插入数据
    thinkphp多层volist实现多表查询
    数据转换
    循环赛日程安排问题
    JS中setTimeout()的使用方法具体解释
  • 原文地址:https://www.cnblogs.com/lanpang9661/p/12582456.html
Copyright © 2011-2022 走看看