gpt4 book ai didi

javascript - React 在第三方库的回调中丢失 "this"

转载 作者:行者123 更新时间:2023-12-02 21:03:45 26 4
gpt4 key购买 nike

在 React 中,我使用 Quagga.js 库来解码来自网络摄像头的条形码。

除了在扫描条形码时 Quagga 调用的“OnDetected”函数之外,一切工作正常。当来自回调时,React 代码将失去对 React 组件的“this”的访问。

下面是代码,当从 Quagga.onDetected(this.onDetected); 作为回调调用时,问题会在 onDetected(result) 函数中发挥作用

如果觉得这个问题更多的是对 React 本身的误解,而不是库有问题。如果是这种情况,我们将非常感谢一些与第三方库合作的一般原则。

onDetected(result) {
this.processBarcode(result["codeResult"]["code"]); //<- "this" refers to the callback, not the react component
}

processBarcode(barcode) {
if (barcode.startsWith("US-")) {
this.setState({user_barcode: barcode});
} else {
this.setState({shop_drawing_barcode: barcode});
}
}

componentDidMount() {
(new Promise((resolve, reject) => {
Quagga.init({
inputStream: {
name: "Live",
type: "LiveStream",
target: document.querySelector('#scanner_window'), // Or '#yourElement' (optional)
constraints: {
width: 480,
height: 480,
facingMode: "environment" // or user
}
},
numOfWorkers: 1,
decoder: {
readers: ["code_128_reader"]
}, locate: true

}, (err) => {
Quagga.start();
console.log("Initialization finished. Ready to start");
resolve();
})
})).then(() => {
//Set the callback
Quagga.onDetected(this.onDetected);
});
}

最佳答案

this.onDetected 可能会传递函数而不绑定(bind)到任何 this。您必须显式绑定(bind) this.onDetected

Quagga.onDetected(this.onDetected.bind(this));

关于javascript - React 在第三方库的回调中丢失 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61275885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com