繁体   English   中英

React 在第三方库的回调中丢失了“this”

[英]React Loses “this” In Callback From Third Party Library

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

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

下面是代码,问题在onDetected(result) function 作为Quagga.onDetected(this.onDetected);

如果觉得这个问题更多的是对 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 可能会通过 function 而不绑定到任何 this。 您必须明确绑定 this.onDetected

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM