首页 > 解决方案 > 如何在打字稿类中调用反应组件内部定义的函数?

问题描述

 export class abc extends React.Component<IProps, IState> {
    function(name: string) {
    console.log("I wish to call this function"+ name);
    }

render() {
    return (
      <div>Hello</div>
    );
  }
}

现在我想将上面定义的组件的函数方法调用到另一个 xyz.ts 类(不是反应组件)中是否可以这样做?

标签: javascriptreactjstypescriptreact-component

解决方案


您可以像这样使用侦听器模式:

export interface IListener {
    notify: (name:string) => void;
}


export class Listener {
    listener : IListener[] = [];


    addListener(listener: IListener) {
      this.listener.add(listener)
    }

    notifyListener() {
      this.listener.forEach((listener) => {
          listener.notify("abc");
      });
    }
  }

  export class abc extends React.Component<IProps, IState> implements IListener {

    componentDidMount() {
        // register this class as a listener
        new Listener().addListener(this);
    }

    public notify(name:string) {
        this.test(name);
    }

    test(name: string) {
      console.log("I wish to call this function"+ name);
    }
    render() {
      return (
      <div>Hello</div>);
    }
    
  }

推荐阅读