什么是高阶组件
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);
本文介绍了React中的高阶组件概念及其应用方式。高阶组件是一种用于增强现有组件功能的模式,通过包裹原始组件来增加新的行为或状态。文章提供了一个具体的实现示例,展示了如何为已有组件添加onClick事件。

1万+

被折叠的 条评论
为什么被折叠?



