[英]react-native dynamically changing view height using ternary operator
I am trying to dynamically change view height using a ternary operator. 我正在尝试使用三元运算符动态更改视图高度。
First I get the screen height of the device 首先我得到设备的屏幕高度
const {
height: SCREEN_HEIGHT,
} = Dimensions.get('window')
const IS_IPHONE_X = SCREEN_HEIGHT === 812
const IS_IPHONE_XR = SCREEN_HEIGHT === 896
const IS_IPHONE_SIX = SCREEN_HEIGHT === 667
Second, I check if the device is iphoneX
其次,我检查设备是否为
iphoneX
const IMAGE_BAR_HEIGHT = Platform.OS === 'ios' ?( IS_IPHONE_X ? 332 : 368): 0
Using a ternary operator is good but I can only check two device with the code above. 使用三元运算符很好,但是我只能使用上面的代码检查两个设备。
Is there a way I could use multiple conditions in a ternary operator? 有没有办法可以在三元运算符中使用多个条件? I tried this.
我试过了 But gives me an error:
但是给我一个错误:
const IMAGE_BAR_HEIGHT = Platform.OS === 'ios' ?( IS_IPHONE_X ? 332 : IS_IPHONE_XR ? : 368 : IS_IPHONE_SIX : 300) : 0
You can for sure achieve this with Ternary operator but it is not advised to use nested ternaries. 您可以肯定地使用三元运算符实现此目标,但不建议使用嵌套三元数。 I would suggest to use
if else
here instead of ternary. 我建议在这里使用
if else
代替三进制。
let height = 0;
if (Platform.OS === 'ios') {
if (IS_IPHONE_X) {
height = 332;
} else if (IS_IPHONE_XR) {
height = 368;
} else if (IS_IPHONE_SIX) {
height = 300;
}
}
If you want to do this with ternary only then 如果只想使用三元组,则
const height = Platform.OS === 'ios' ? (IS_IPHONE_X ? 332 : (IS_IPHONE_XR ? 368 : (IS_IPHONE_SIX ? 300 : 0))) : 0;
It is better to use logical operator with ternary operator. 最好将逻辑运算符与三元运算符一起使用。
const IMAGE_BAR_HEIGHT = Platform.OS === 'ios' ? ( IS_IPHONE_X && 332 || IS_IPHONE_XR && 368 || IS_IPHONE_SIX && 300) : 0
Or I recommend split code. 或者我建议使用拆分代码。
const SCREEN_HEIGHT = Dimensions.get('window').height;
iOSDeviceInfo = () => {
switch (SCREEN_HEIGHT) {
case 812:
return 'X';
case 866:
return 'XR';
case 667:
return 'SIX';
default:
break;
}
}
const IMAGE_BAR_HEIGHT = {
X: 332,
XR: 368,
SIX: 300,
}
const imageHeight = Platform.OS === 'ios' ? IMAGE_BAR_HEIGHT[iOSDeviceInfo()] : 0
Not tested. 未经测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.