Implement two-way help binding yourself in react

function bind(component,arr){
    const _com={};
    arr.forEach(item => {
        _com[item]=component.item;
        Object.defineProperty(component,item,{
            get:function(){
                return _com[item]
            },
            set: function(v){
                _com[item]=v;
                component.setState({[item]:_com[item]})
            }
        })
    });

}
class Test{
    constructor(){
        this.a=1;
        this.b=2;
        bind(this,["a","b"])
    }
    setState(obj){
        console.log(obj)
    }

}
var t=new Test();
t.a=100;
console.log(t.a)

 

Published 21 original articles · won praise 2 · Views 7283

Guess you like

Origin blog.csdn.net/qq_31261131/article/details/81160195