猿问

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

 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 类(不是反应组件)中,是否可以做同样的事情?


慕盖茨4494581
浏览 120回答 2
2回答

尚方宝剑之说

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

拉莫斯之舞

您可以像这样使用侦听器模式:export interface IListener {&nbsp; &nbsp; notify: (name:string) => void;}export class Listener {&nbsp; &nbsp; listener : IListener[] = [];&nbsp; &nbsp; addListener(listener: IListener) {&nbsp; &nbsp; &nbsp; this.listener.add(listener)&nbsp; &nbsp; }&nbsp; &nbsp; notifyListener() {&nbsp; &nbsp; &nbsp; this.listener.forEach((listener) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listener.notify("abc");&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; }&nbsp; export class abc extends React.Component<IProps, IState> implements IListener {&nbsp; &nbsp; componentDidMount() {&nbsp; &nbsp; &nbsp; &nbsp; // register this class as a listener&nbsp; &nbsp; &nbsp; &nbsp; new Listener().addListener(this);&nbsp; &nbsp; }&nbsp; &nbsp; public notify(name:string) {&nbsp; &nbsp; &nbsp; &nbsp; this.test(name);&nbsp; &nbsp; }&nbsp; &nbsp; test(name: string) {&nbsp; &nbsp; &nbsp; console.log("I wish to call this function"+ name);&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>Hello</div>);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答