根据reactJs官方文档的定义,HOC如下:
简要来讲的话,是一种重复利用组件逻辑的技术,接受一个组件,并且返回一个组件。
就上上面的例子一样,会接受WrappedComponent然后返回enhancedComponent.下面举例子来讲解。
1.创建一个按钮组件,并且监听点击次数
import React, { Component, useState, useEffect } from "react";
class ClickCounter extends Component {
constructor() {
super();
this.state = {
count: 0
};
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount() {
this.setState(preveState => {
return {
count: preveState.count + 1
};
});
}
render() {
let { count } = this.state;
return (
<div>
<button onClick={this.incrementCount}>Clic