Javascript:将回调函数发送给类构造函数

时间:2019-03-07 14:08:17

标签: javascript reactjs react-native oop callback

可能有一个非常简单的解决方案,但是我正在寻找一种方法将回调函数发送到类的构造函数,并使用该回调函数来更新原始类中的状态 (在本机反应中)。

这是到目前为止我得到的:

export class A extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bluetooth: {
        isConnected: "false",
        preventAutoReconnect: false,
        connected: {
          id: "",
          name: "none",
          obj: {}
        }
      }
    };
    this.b = new Bluetooth(this.updateBleContext);
  }

  updateBleContext = bleInfo => {
    console.log("updating context");
    this.setState({
      bluetooth: bleInfo
    });
  };
}

尝试这样使用:

export default class B {
  constructor(updateContext) {
    this.bluetooth = {
      isConnected: "false",
      preventAutoReconnect: false,
      connected: {
        id: "",
        name: "none",
        obj: {}
      }
    };
    this.updateContext = updateContext();
  }

  setDisconnected = () => {
    let bluetooth = this.bluetooth;
    bluetooth.connected.name = "";
    bluetooth.connected.obj = {};
    bluetooth.isConnected = "false";

    this.updateContext(bluetooth);
    this.bluetooth = bluetooth;
  };
}

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您已将函数正确传递到B类中。

B类构造函数中,您具有:

this.updateContext = updateContext();

这会将this.updateContext分配给函数调用updateContext();的返回值,在这种情况下为undefined

如果您想将函数存储在B类中,则可以:

this.updateContext = updateContext;

然后,您将可以访问该函数并能够按预期方式调用它: this.updateContext(bluetooth);

export default class B {
  constructor(updateContext) {
    this.bluetooth = {
      isConnected: "false",
      preventAutoReconnect: false,
      connected: {
        id: "",
        name: "none",
        obj: {}
      }
    };
    this.updateContext = updateContext;
  }

  setDisconnected = () => {
    let bluetooth = this.bluetooth;
    bluetooth.connected.name = "";
    bluetooth.connected.obj = {};
    bluetooth.isConnected = "false";

    this.updateContext(bluetooth);
    this.bluetooth = bluetooth;
  };
}