什么是高阶组件
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);