模拟React 的PropTypes,检查props参数,并附初始值。

闲来无聊,按照自己平时使用React 的PropTypes,使用class,Proxy,Reflect简单实现了一个自己的PropTypes。 只是个人学习用,有不对的地方欢迎指教,不喜勿喷。

// 检查是否符合条件类
class PropTypes{
    static any = ''
    static object = 'Object'
    static bool = 'Boolean'
    static string = 'String'
    static number = 'Number'
    static array = 'Array'
    static func = 'Function'
    static propEqual(value,type){
        return type ? Object.prototype.toString.call(value) === '[object ' + type + ']' :true;
    }
    static checkType(param = {},proptypes = {}){
        let arr = []
        for(let key in proptypes){
             if(!PropTypes.propEqual(param[key] , proptypes[key])){
                    arr.push(`props参数${key}应该为${proptypes[key]}格式`)                 
             }
        }
        return arr;
    }
}
// 代理重新生成props的值,只能查看,不能修改
 function proxyObject(target = {}) {
     return new Proxy(target,{
         set() {
             console.log('不允许修改props的参数')
         },
         get(obj, prop) {
             return Reflect.get(obj, prop)
         }
     })
 }
// 这里代理类的构造函数,调用构造函数前检查props参数的类
// 其实也可以写到类的构造函数里,用这种方法如果还有类需要检查props参数,就不用再写一遍了
function constructProxy(target){
    return new Proxy(target,{
        construct(a,b,{propTypes={},defaultProps={}}={}){
            let props = b[0] || {};
            props = proxyObject({...defaultProps,...props})
            let warn = PropTypes.checkType(props,propTypes);
            if(warn.length>0){
                console.warn(warn.join('\r\n'))
                console.warn('参数不一致会发生未知的错误,请检查传递的参数')
            }
         return Reflect.construct(target, [props])
        }
    })
}
// 使用构造函数代理生成的class Component

var Component = constructProxy(class {
    constructor(props){
        console.dir(new.target)
        this.props = props;
    }
})
// react有一个基类,所有的组件都继承Component类,这里简单的模拟了一下
// Com类
class Com extends Component{
     constructor(props){
        super(props)
        console.log(this.props.a) // 可以读取 输出c
        this.props.a = ''// 修改会报错
     }
 }
 // Com的props参数类型
 Com.propTypes = {
   a:PropTypes.number,
   b:PropTypes.bool
 }
 // Com的props默认参数
 Com.defaultProps = {
    a:'c'
 }
 new Com()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值