简体   繁体   English

React:Typescript/Javascript 接口作为回调并访问 state

[英]React: Typescript/Javascript Interface as Callback and accessing state

as a former Java Engineer I'm struggling to have an interface as callback in Typescript/Javascript.作为一名前 Java 工程师,我正在努力在 Typescript/Javascript 中使用接口作为回调。

I'm having a "worker" class where I call doWork(..., myWorkerCallback) The callback consists of different callback methods.我有一个“工人” class 我调用doWork(..., myWorkerCallback)回调由不同的回调方法组成。

interface WorkerCallback {
    onWorkDone() : void
    onError(message: String) : void
    ...
}

In my calling component I'd have a member that implements that Callback-Interface.在我的调用组件中,我将有一个实现该回调接口的成员。

myWorkerCallback: WorkerCallback = {
    onWorkDone() {
    ...
    }
}

now I need to access the state of the React component inside these callback methods.现在我需要在这些回调方法中访问 React 组件的 state。 So I need to bind this callback member, right?所以我需要绑定这个回调成员,对吧? But how to bind this interface member但是如何绑定这个接口成员

I am not sure about react-native but typical way to bind something to function is to use closures:我不确定 react-native 但将某些东西绑定到 function 的典型方法是使用闭包:

interface IWorkerCallback {
    onWorkDone(): void;
    onError(message: string): void;
    // ...
}

// Option 1: using object literals
function makeWorkerCallback(state: SomeState): IWorkerCallback  {
    return {
        onWorkDone: () => {
            state.update();
        },
        onError: () => { }
    }
}

// Option 2: using classes
class WorkerCallback implements IWorkerCallback {
    state: SomeState;

    constructor(state: SomeState) {
        this.state = state;
    }

    onWorkDone() {
        this.state.update();
    }

    onError(message: string) { }
}

// Usage example
const myWorkerCallback1 = makeWorkerCallback(state1);
const myWorkerCallback2 = makeWorkerCallback(state2);

const myWorkerCallback3 = new WorkerCallback(state3);
const myWorkerCallback4 = new WorkerCallback(state3);

Though at this point these objects are not callbacks.尽管此时这些对象不是回调。 They are more.他们更多。 I would rename them "FooBarHandler" or something.我会将它们重命名为“FooBarHandler”之类的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM