【问题标题】:Javascript: Sending callback function to class constructorJavascript:向类构造函数发送回调函数
【发布时间】:2019-03-07 14:08:16
【问题描述】:

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

这是我目前所得到的:

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

非常感谢任何帮助!

【问题讨论】:

  • classB 是从 classA 渲染的吗?如果是这样,只需在 classA 的渲染中传递 updateBleContext。
  • 它不作为组件使用,我实际上并没有在B类中导入react。

标签: javascript reactjs react-native oop callback


【解决方案1】:

您正确地将函数传递给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;
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2021-10-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    相关资源
    最近更新 更多