如何将值存储在 onChange 函数的全局变量中?

How To Store Value in Global Variable from onChange Function?

我需要从 onChange 函数访问 returned 值,但它没有读取任何内容,因为它显然没有正确存储。这是我的代码:

HTML:

<input type="file" accept="image/*" name="UploadBox" className="custom-file-input" id="UploadBox" onChange={this.onChange} />

JS:

onChange = (e) => {
        this.setState({
            selectedImage: e.target.files[0]
        })

        let files = e.target.files;
        let file = e.target.files[0];

        if (files.length > 0 && file) {
            this.getBase64(files[0]);
        }
    }

    getBase64(file) {
        let reader = new FileReader();

        console.log(file);

        reader.onload = function () {
            console.log(reader.result);
            let binaryString = reader.result;
            let btoaString = btoa(binaryString);
            //console.log(btoaString);
            return binaryString;
        }

        reader.readAsDataURL(file);

        reader.onerror = function (error) {
            console.log('Error: ', error);
        }
    }

进一步向下这是我需要在 imageBase64Function 变量中存储 return 值的地方:

let imageBase64Function = this.getBase64();

当我执行 reader.result 的 console.log 时,我得到了正确的 base64 信息。但我需要将它存储在 imageBase64 变量中。我试过研究全局变量和赋值,但我知道我做错了什么。非常感谢任何帮助,谢谢!

编辑:尝试设置状态并通过删除开头的元数据使用 base64 字符串后解决

constructor (props) {
        super(props);
        this.state = {
            selectedImage: null,
            errors: {}
        }
        this.onChange = this.onChange.bind(this);
        this.getBase64 = this.getBase64.bind(this);
    }

onChange = (e) => {
        this.setState({
            selectedImage: e.target.files[0]
        })

        let files = e.target.files;
        let file = e.target.files[0];

        if (files.length > 0 && file) {
            this.getBase64(files[0]);
        }
    }

    getBase64(file) {
        let reader = new FileReader();

        console.log(file);

        reader.onload = function () {
            console.log(reader.result);
            let binaryString = reader.result;
            let base64OrigString = binaryString.split('base64,');
            let base64Split = base64OrigString[1];
            //return binaryString;
            this.setState({selectedImage: base64Split})
        }.bind(this)

        reader.readAsDataURL(file);

        reader.onerror = function (error) {
            console.log('Error: ', error);
        }
    }

您可以调用 this.setState({ selectedImage: binaryString }) 而不是返回 binaryString。正如您在测试中发现的那样,您需要取消 bind(this) 以便可以从嵌套函数中调用 this.setState。另一种可能的解决方案是保持绑定不变,但更改调用匿名 reader.onload 函数的方式。这将保留外部 this 并允许您从块内访问 this.state

reader.onload = () => { … }