gpt4 book ai didi

react-native - 如何更新变量 react native ?

转载 作者:行者123 更新时间:2023-12-04 03:46:50 28 4
gpt4 key购买 nike

我有一个应用程序,我需要在其中获取图片的已知比例以便稍后调整大小。用户可以水平和垂直拍摄照片。当然,比例也会发生变化。所以我需要得到两个不同的比率。

更新 let horizo​​ntalImageRatio = 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();

最佳答案

因此,显然,您无权访问 horizo​​ntalRatioCalc 内部的 horizo​​ntalImageRatio,方法 horizo​​ntalRatioCalc 具有不同的范围。您可以做的是更改 horizo​​ntalRatioCalc 以接收一个参数并返回一个值,就像我在这个示例中所做的那样:https://stackblitz.com/edit/react-xiysai这很好,因为现在您有一个可以独立测试的函数。

或者你也可以这样做: https://stackblitz.com/edit/react-variable-scope这样您就可以访问变量和方法。

关于react-native - 如何更新变量 react native ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65021590/

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