React 高阶组件

什么是高阶组件

Higher-Order Components (HOCs) are JavaScript functions which add functionality to existing component classes.

当我们在使用React的Component时,经常会遇到这种情况,要用的组件已经有了,但是其中传递的参数或某些功能不满足我们的要求,这时候要怎么办,

  • 从写组件,
  • 找到组件源文件进行修改、
  • 高阶组件。

对于一些简单的组件或许我们还可以从写,但是复杂的可能就不可以了,如果你选择修改源文件那也只能呵呵;

高阶组件

此组件为一个高阶组件生成器,将需要修改的组件

import React, { Component } from 'react';

export const Enhance = (ComposedComponent) => class extends Component {
  constructor(props) {
    super();
    this.state = {
      data: null,
    }
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.props.onClicked(this.props.data);
  }
  componentDidMount() {
    //if (this.props.data.checked == false) return;
  }
  render() {
    return <ComposedComponent { ...this.props } data={ this.state.data }
                                                onClick={ this.handleClick }/>
  }
}

调用Enhance,此组件就增加了 onClick 属性

import React, { Component } from 'react';
import { Enhance } from './Enhance';
import { Marker } from 'react-leaflet';

export default Enhance(Marker);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值