这可能是一个非常简单的解决方案,但我正在寻找一种方法将回调函数发送到类的构造函数并使用该回调函数来更新原始类中的状态(在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;
};
}
任何帮助是极大的赞赏!
您正确地将函数传递给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;
};
}