React 高阶组件(HOC)
高阶组件(HOC)是 React 中用于复用组件逻辑的一种高级技巧。
1. 简单用法
import React, { Component } from "react";
const withMouse = (AppComponent) => {
class HOC extends Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
}
bindMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY,
});
};
render() {
return (
<div
style={{ border: "1px solid #eee", height: 400, width: 400 }}
onMouseMove={this.bindMouseMove}
>
<h5>高阶组件</h5>
<AppComponent {...this.props} mousePosition={this.state} />
</div>
);
}
}
return HOC;
};
const App = (props) => {
const { x, y } = props.mousePosition;
return (
<p>
mousePosition position is ({x}, {y})
</p>
);
};
<!--高阶组件 withMouse -->
export default withMouse(App);
redux 中 connect
import { connect } from "react-redux";
const TodoList = connect(mapStateToProps, mapDispatchToProps)(TodoList);
export default TodoList;
connect也是一个高阶组件:
export const connect = (mapStateToProps, mapDispatchToProps) => (
WrappedComponent
) => {
class Connect extends Component {
constructor(props) {
super(props);
this.state = {
allProps: {},
};
}
/*
中间省略公共逻辑
mapStateToProps = (state) => {
return { allProps: state.allProps };
};
mapDispatchToProps = (dispatch) => {
return { ... };
};
*/
render() {
return <WrappedComponent {...this.state.allProps} />;
}
}
return Connect;
};