react 高阶组件
摘要
高阶组件为了解决抽象基础组件的通用方法/属性,给多个基础组件增加buffer。如果立足基础组件理解,则高阶组件是有个经验加成的基础组件,基础组件继承于高阶组件。
写法
mixin 写法
包裹型写法,如下 a 即为 b 的高阶组件, 纯函数式编程, 可用串联式编写
const a = enhance(b);
const c = enhance1(enhance2(b));
包裹型可以实现渲染劫持, 由高阶组件控制基础组件的渲染方式。
function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
const elementsTree = super.render()
let newProps = {};
if (elementsTree && elementsTree.type === 'input') {
newProps = {value: 'may the force be with you'}
}
const props = Object.assign({}, elementsTree.props, newProps)
const newElementsTree = React.cloneElement(elementsTree, props, elementsTree.props.children)
return newElementsTree
}
}
}
decorator 写法
装饰器写法,
@a
class b extends c {
}
优缺点
mixin
mixin 并不是非常推荐的方法。
缺点:
- 一个组件和它的 mixin 之间的关联是隐式的。
- 单一组件中使用多个 mixin 时会产生冲突。
- 性能优化变复杂
计划、执行、每天高效的活着学着