如何在打字稿 class 中调用反应组件内定义的函数?

How to call a function defined inside react component in a typescript class?

 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 class(不是react组件)可以吗?

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

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>);
    }
    
  }

如果你想在不同的 ts 文件中使用它,你绝对应该将函数移出组件并导出它。