我有一个应用程序,我需要知道图片的比例,以便稍后调整大小。用户可以水平和垂直拍照。当然,比例也会发生变化。所以我需要得到两个不同的比率。
更新let horizontalImageRatio = 0;
时出现问题
我该怎么解决这个问题,有什么建议吗?
我的代码:
Image.getSize(data.uri, (width, height) => { // Pickuping size of the picture
let imageWidth = width;
let imageHeight = height;
let stringImageWidth = '' + imageWidth; // Make double to string for storing to asyncstorage
let stringImageHeight = '' + imageHeight;
let horizontalImageRatio = 0; // this value should be updated
let verticalImageRatio = 0;
// For updating let horizontalImageRatio, but not working outside of this <-- PROBLEM
const horizontalRatioCalc = () => {
horizontalImageRatio = imageWidth/imageHeight;
console.log('horizontal_update', horizontalImageRatio);
};
const verticalRatioCalc = () => {
verticalImageRatio = imageWidth/imageHeight;
console.log('vertical_update', verticalImageRatio);
};
let stringHorizontalImageRatio = '' + horizontalImageRatio;
let stringVerticalImageRatio = '' + verticalImageRatio;
console.log(`Size of the picture ${imageWidth}x${imageHeight}`); // Tells size of the image for the console
horizontalRatio = async () => {
if (imageHeight>imageWidth) {
verticalRatioCalc();
try {
AsyncStorage.setItem("imageVerticalRatio", stringVerticalImageRatio),
AsyncStorage.setItem("asyncimageWidth", stringImageWidth)
AsyncStorage.setItem("asyncimageHeight", stringImageHeight)
console.log(`Vertical ratio saved! It's ${stringVerticalImageRatio}`)
console.log(`Image Width saved! It's ${stringImageWidth}`)
console.log(`Image height saved! It's ${stringImageHeight}`)
} catch (e) {
console.log(`AsyncStorage saving of image vertical ratio cannot be done.`)
}
}else {
horizontalRatioCalc();
try {
AsyncStorage.setItem("imageHorizontalRatio", stringHorizontalImageRatio),
AsyncStorage.setItem("asyncimageWidth", stringImageWidth)
AsyncStorage.setItem("asyncimageHeight", stringImageHeight)
console.log(`Horizontal ratio saved! It's ${stringHorizontalImageRatio}`)
console.log(`Image Width saved! It's ${stringImageWidth}`)
console.log(`Image height saved! It's ${stringImageHeight}`)
} catch (e) {
console.log(`AsyncStorage saving of image vertical ratio cannot be done.`)
}
}
}
horizontalRatio();
因此,显然,您无法访问horizontalRatioCalc内部的horizontalImageRatio,方法horizontalRatioCalc具有不同的作用域。您可以更改horizontalRatioCalc以接收参数并返回值,就像我在本例中所做的那样:https://stackblitz.com/edit/react-xiysai这很好,因为现在你有了一个可以独立测试的功能。
或者你也可以这样做:https://stackblitz.com/edit/react-variable-scope通过这种方式,您可以同时访问变量和方法。