【发布时间】: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