Javascript:向类构造函数发送回调函数

问题描述 投票:0回答:1

这可能是一个非常简单的解决方案,但我正在寻找一种方法将回调函数发送到类的构造函数并使用该回调函数来更新原始类中的状态(在react-native 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;
  };
}

任何帮助是极大的赞赏!

javascript reactjs react-native oop callback
1个回答
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;
  };
}
© www.soinside.com 2019 - 2024. All rights reserved.