美文网首页
react中 ts注入器的使用

react中 ts注入器的使用

作者: 魔仙堡杠把子灬 | 来源:发表于2021-01-05 16:28 被阅读0次

你羡慕的生活背后都是你熬不起的苦

我的github: 李大玄
我的私人博客: 李大玄
我的npm开源库: 李大玄
我的简书: 李大玄
我的CSDN: 李大玄
我的掘金: 李大玄
哔哩哔哩: 李大玄

  1. class中函数注入
    好比 原来的点击事件是每次只增加一个数 但是加上函数注入 每次就增加三个数
function addTwo() {
  return function (target: any, methodName: string, descriptor: PropertyDescriptor) {
    const fun = descriptor.value;
    descriptor.value = async function () {
      const self: any = this;
      try {
        const data = await fun.bind(self)();
      } catch (error) {
        // error
      }
      const num = self.state.num + 2;
      self.setState({
        num
      });
    };
  };
}


export default class In extends Component<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>
    );
  }
}
  1. class注入
    原来的类中只有增加方法 但是没有减少 使用类注入就可以增加一个减一的方法
function Class() {
  return function (target: any): any {
    return class extends 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()
export default class In extends Component<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>
    );
  }
}

相关文章

网友评论

      本文标题:react中 ts注入器的使用

      本文链接:https://www.haomeiwen.com/subject/mrrwoktx.html