The life you envy is all about suffering you can’t afford

Github: Lee Dahyun My private blog: Lee Dahyun my NPM open source library: Lee Dahyun My Brief book: Lee Dahyun My CSDN: Lee Dahyun My Gold Digger: Lee Dae-hyun Billie Billie: Lee Dae-hyun

  1. Function injection in class

For example, the original click event increment is one number at a time but adding function injection increment is three numbers at a time

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() // Here is function injection
  add() {
    const num = this.state.num + 1;
    this.setState({
      num
    });
  }
  render() {
    return (
      <div>
        <Button onClick={this.add}>Gal.</Button>
        <br/>
        {this.state.num}
      </div>); }}Copy the code
  1. The class into

Using class injection, you can add a method minus one

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}>Gal.</Button>
            {this.state.num}
            <Button className="ml10" onClick={this.del}>Minus one</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}>Gal.</Button>
        <br/>
        {this.state.num}
      </div>); }}Copy the code