时间: 2019-10-23阅读: 73标签: Component事实性错误:
一、mixin
什么是mixin:创造一种类似多重继承的效果。事实上,说它是组合更为贴切。
那 vue 呢?它连 HOC 都没有,render props 更不现实(jsx自带)
1.封装mixin方法实例:
const mixin = function(obj,mixins){
const newObj = obj;
newObj.prototype = Object.create(obj.prototype);
for(let prop in mixins){
if(mixins.hasOwnProperty(prop)){
newObj.prototype[prop] = mixins[prop];
}
}
return newObj;
}
const BigMixin = {
fly:()=>{
console.log('I can fly');
}
}
const Big = function(){
console.log('new big');
}
const FlyBig = mixin(Big,BigMixin); // new big
const flyBig = new FlyBig(); // I can fly
对于广义的mixin方法,就是用赋值的方式将mixin对象里的方法都挂载到原对象上,来实现对象的混入。
HOC
2.在React中使用mixin
React在使用createClass构建组件时提供了mixin属性。(ES6 classes形式构建组件时,不支持mixin)
实例:
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin'; //官方封装的mixin对象
React.creatClass({
mixins:[PureRenderMixin],reder(){
return <div>foo</div>;
}
});
注:mixins属性可以指定多个mixin。但,如果两个mixin(也就是两个对象)中有名称相同的方法,会报命名冲突错误。
使用createClass实现的mixin可以为组件做两件事:
(1)定义工具方法。用mixin混入写好的工具方法。在需要用到工具方法的组件中设置mixin,即可使用相应工具方法。
(2)生命周期继承,props、state的合并。如果多个mixin对象中,都定义了同一个生命周期,react会智能地将它们合并起来执行。
const DefaultButton = { props: { text: String }, template: `button{{text}}/button`}function wrap(comp) { return { components: { comp }, template: `comp text="123"/` }}new Vue({ components: { TextButton: wrap(DefaultButton) }, template: `text-button /`})
3.ES6 Classes 与 decorator
es6 classes语法,用decorator实现mixin。
注:decorator与Java中pre-defined annotation的区别是,decorator是运用在运行时的方法。
HOC + render props
const DefaultButton = { props: { renderText: Function }, render(h) { return h('button', this.renderText()) }}function wrap(comp) { return { render(h) { return h(comp, { attrs: { renderText: () = "123" } }) } }}const textButton = wrap(DefaultButton)new Vue({ render(h) { return h(textButton) }})
4.mixin存在的问题
(1)破坏了原有组件的封装。
mixin中的方法会带来新的state和props,及其他未知操作,在使用组件中不可知,无法有目的地控制。
(2)命名冲突。
多个mixin中,或mixin与当前组件,可能存在相同命名的方法,从而命名冲突。
(3)增加复杂性。
当添加了越来越多的mixin,就会引入越来越多的方法,从而造成代码逻辑复杂,不易维护。
react 的不可变,纯函数。直接导致 hooks 必须使用 const 关键字,不能是 let,这也是 hooks 的奇迹之一
二、高阶组件
const keyword 和 "不可变,纯函数" 有什么关系, 若使用 let、var, 是否不能实现hook?
1.高阶函数:
概念:接受函数作为输入,或是输出一个函数,的函数。
如常用的map、reduce、sort等,都是高阶函数。
本文由10bet发布于Web前端,转载请注明出处:10bet:react组件间抽象(mixin与高阶组件)
关键词: