zoukankan      html  css  js  c++  java
  • react-native 高阶组件笔记

    何为高阶组件:通过函数向现有组件类添加逻辑,一个React组件包裹另外一个React组件,就是高阶组件HOC(Higher Order Component)
    高阶函数概念来源于JavaScript的高阶函数:高阶函数就是接受函数作为输入或者输出的函数
     
     
    在React Native开发中开发思路是通过组合各种组件来组织APP,不提倡使用继承 所以使用高阶组件对于替换一些已有组件更可靠.
     
    高阶函数定义中”包裹”的概念,有两种不同的含义:
    Props Proxy (PP-属性代理): HOC 对传给 WrappedComponent W 的 porps 进行操作,
    Inheritance Inversion (II-反向继承): HOC 继承 WrappedComponent W
     

    Props Proxy

    const HOC = (WrappedComponent) => class WarppedComponent extends Component{
     
        render() {
            return <WrappedComponent {...this.props} />    }
    }
    //普通的组件class WrappedComponent extends Component{
        render(){
            //....    }
    }
     
    export  default  HOC(WrappedComponent)
     

    操作props

      我们看到之前要传递给被包裹组件WrappedComponent的属性首先传递给了高阶组件返回的组件(WrapperComponent),这样我们就获得了props的控制权(这也就是为什么这种方法叫做属性代理)。我们可以按照需要对传入的props进行增加、删除、修改(当然修改带来的风险需要你自己来控制),举个例子:
    const HOC = (WrappedComponent) => class WrapperComponent extends Component { render() { const newProps = { name: 'HOC' } return <WrappedComponent {...this.props} {...newProps} />; } }
     
     
     

    反向继承

                      反向继承是指返回的组件去继承之前的组件(这里都用WrappedComponent代指)
        const HOC = (WrappedComponent) => class extends WrappedComponent { render() { return super.render(); } } 
  • 相关阅读:
    【leetcode】974. Subarray Sums Divisible by K
    【leetcode】976. Largest Perimeter Triangle
    【leetcode】973. K Closest Points to Origin
    listen 70
    科学60秒 (一) :上
    listen 69
    listen 68 Theoretical Physicist Stephen Hawking Dies at 76
    中译英33
    listen 67
    中译英32
  • 原文地址:https://www.cnblogs.com/air-liyan/p/7155389.html
Copyright © 2011-2022 走看看