React Native创建高阶组件(修饰器)

创建

两种方式:

代理方式的高阶组件

function containerWrapper(Container, otherProps) {
  // 也可以使用无状态组件
  class WrappedComponent extends Component {
    componentWillMount() {
      // Container的componentWillMount也会执行
      console.log('wrapper')
    }
    
    render() {
      return (
        <View style={{flex: 1}}>
          <Container {...this.props} {...otherProps}/>
        </View>
      )
    }
  }
  // 或者
  // let WrappedComponent = (props) => (
  //   <View style={{flex: 1}}>
  //     <Container {...props} {...otherProps}/>
  //   </View>
  // )
  return connect(
    state => ({state}),
    dispatch => ({actions: bindActionCreators(actions, dispatch)})
  )(WrappedComponent);
}

继承方式的高阶组件

function containerWrapper(Container) {
  // 继承Container
  class WrappedComponent extends Container {
    componentWillMount() {
      // 需要调用super
      super.componentWillMount()
      console.log('wrapper')
    }
    render() {
      return (
        <View style={{flex: 1}}>
          {super.render()}
        </View>
      )
    }
  }

  return connect(
    state => ({state}),
    dispatch => ({actions: bindActionCreators(actions, dispatch)})
  )(WrappedComponent);
}

调用

export default containerWrapper(TopicPage, {statusTextStyle: 'dark'})

两种方式都可以包装组件、扩展生命周期方法。
不同点是前者实际创建了两个组件,后者因为是继承,所以只有一个;前者可以增删props,后者没找到控制props的方法。

RNN通过组件的静态属性来设置navigator,使用代理方式的高阶组件包裹后,访问不到这些静态属性,需要在高阶组件中加入两行。如果是继承方式就不需要

static navigatorStyle = Container.navigatorStyle
static navigatorButtons = Container.navigatorButtons

使用修饰器

引入修饰器(Decorator)简化代码,模仿connect修改高阶组件

作为高阶组件,都有必要转换为修饰器实现

一、npm i --save-dev babel-plugin-transform-decorators-legacy

修改.babelrc

{
    "presets": ["react-native"],
    "plugins": ["transform-decorators-legacy"]
}

二、模仿redux connect修改container的高阶组件。分解为两层函数,第一层的参数为需要的props,第二层的参数为组件

export const containerWrapper = (title) => {
  return (Container)=>{
    let WrappedComponent = (props)=> <Container {...props} title={title}/>
    ...
    return WrappedComponent
  }
}

三、调用

普通方式:

class TopicPage extends Component {...}
export default containerWrapper({title: '话题'})(TopicPage)

修饰器调用:

@containerWrapper({title: '话题'})
export default class TopicPage extends Component {...}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在目前的前端社区,『推崇组合,不推荐继承(prefer composition than inheritance)...
    Wenliang阅读 77,717评论 16 124
  • 高阶组件是对既有组件进行包装,以增强既有组件的功能。其核心实现是一个无状态组件(函数),接收另一个组件作为参数,然...
    柏丘君阅读 3,133评论 0 6
  • In this article we will discuss how to use Higher Order C...
    人头原子弹阅读 595评论 0 0
  • 2015年2月18日正是农历年的除夕,晚上十点,看着春晚却突觉一阵寂寞,忍不住写下一些什么。 我已经很多天没有在简...
    环形山阅读 262评论 0 2
  • 小米今天站在衣帽间,奢侈的花了30分钟时间选了一套精神而喜气的红裙子,她不希望被人看出昨晚未睡的狼狈,还特地上...
    旺财杨子阅读 689评论 1 50