functionaddTwo(){returnfunction(target: any,methodName: string,descriptor: PropertyDescriptor){const fun = descriptor.value;
descriptor.value=asyncfunction(){constself: any =this;try{const data =awaitfun.bind(self)();}catch(error){// error}const num = self.state.num +2;
self.setState({
num
});};};}exportdefaultclassInextendsComponent<any, any>{constructor(props: any){super(props);this.state ={num:0,};this.add =this.add.bind(this);}
@addTwo()// 这里是函数注入 add(){const num =this.state.num +1;this.setState({
num
});}render(){return(<div><Button onClick={this.add}>加一</Button><br/>{this.state.num}</div>);}}
class注入 原来的类中只有增加方法 但是没有减少 使用类注入就可以增加一个减一的方法
functionClass(){returnfunction(target: any): any {returnclassextends target {constructor(...args: any[]){super(...args);if(!this.state){this.state ={};}this.del =this.del.bind(this);}del(){const num =this.state.num -1;this.setState({
num
});}render(){return(<div><Button className="mr10" onClick={this.add}>加一</Button>{this.state.num}<Button className="ml10" onClick={this.del}>减一</Button></div>);}};};}
@Class()exportdefaultclassInextendsComponent<any, any>{constructor(props: any){super(props);this.state ={num:0,};this.add =this.add.bind(this);}add(){const num =this.state.num +1;this.setState({
num
});}render(){return(<div><Button onClick={this.add}>加一</Button><br/>{this.state.num}</div>);}}