高阶类 & HOC & anonymous class extends
高阶类 & HOC & anonymous class extends
js 匿名 class extends / mix-ins / 多继承
高阶函数 HOF, 接收一个 function 返回一个新的 function
高阶组件 HOC, 接收一个 component 返回一个新的 component
高阶类 HOC , 接收一个 class 返回一个新的 class
Mix-ins
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Mix-ins
// 匿名 class extends
let calculatorMixin = Base => class extends Base {
calc() { }
};
// 匿名 class extends
let randomizerMixin = Base => class extends Base {
randomize() { }
};
class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) {
//
}
Mixins Considered Harmful
https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html
匿名 class extends
// This function takes a component...
function withSubscription(WrappedComponent, selectData) {
// ...and returns another component...
// return class HOC extends React.Component {
// ✅❓匿名 class extends
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(DataSource, props)
};
}
componentDidMount() {
// ... that takes care of the subscription...
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
// ... and renders the wrapped component with the fresh data!
// Notice that we pass through any additional props
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
Debugging
Wrap the Display Name for Easy Debugging
function withSubscription(WrappedComponent) {
// ✅ 命名 class extends
class WithSubscription extends React.Component {/* ... */}
// 获取 组件名
WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
return WithSubscription;
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
import React, { Component } from 'react';
// 获取组件名
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'HOC Component';
}
// HOC 1. 接收一个组件作为参数
function HOC(WrappedComponent, props) {
// do something
const name = WrappedComponent.name || "hoc";
HOC.displayName = `HOC_${getDisplayName(WrappedComponent)}`;
// HOC 2. 返回一个新组件
// ✅ 匿名 class extends (Anonymous)
// return class extends Component {
// ✅ 命名 class extends ()
return class HOC extends Component {
// constructor(props) {
// super();
// }
render() {
return (
<>
<WrappedComponent props={props} data={name}/>
</>
)
}
}
}
export default HOC;
refs
https://reactjs.org/docs/higher-order-components.html#use-hocs-for-cross-cutting-concerns
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13928692.html
未经授权禁止转载,违者必究!