JavaScript:将回调函数发送到类构造函数



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

这是我到目前为止所拥有的:

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

任何帮助都非常感谢!

您正确地将功能传递到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;
  };
}

相关内容

  • 没有找到相关文章

最新更新