[英]Type Script - React Native : What is the best practice way to write ternary inside ternary?
What is the best practice way to write ternary inside ternary like in my example code?在我的示例代码中,在三元中编写三元的最佳实践方法是什么? I want to make the code more readable and correct and I want to know the correct way to write it.
我想让代码更具可读性和正确性,我想知道编写它的正确方法。
<TouchableOpacity
style={
darkMode
? filterState === 'A'
? styles.activeButtonDark
: styles.buttonDark
: filterState === 'A'
? styles.activeButton
: styles.button
}
>
</TouchableOpacity>
<TouchableOpacity
style={
darkMode
? filterState === 'B'
? styles.activeButtonDark
: styles.buttonDark
: filterState === 'B'
? styles.activeButton
: styles.button
}
>
</TouchableOpacity>
Nested Ternary inside ternary will never be a good approach, readability wise在三元内嵌套三元永远不会是一个好方法,可读性明智
rather than this you can try with :
const darkModeStyle = (filterState) => {
return filterState === 'A' ? styles.activeButtonDark : styles.buttonDark
}
const lightModeStyle = (filterState) => {
return filterState === 'A' ? styles.activeButton : styles.button
}
style = {
darkMode ? darkModeStyle(filterState) : lightModeStyle(filterState)
}
This is still a better approach, or you can use SwitchCase or if else in a separate func.这仍然是一种更好的方法,或者您可以在单独的函数中使用 SwitchCase 或 if else。
Hope it helps.希望能帮助到你。 feel free for doubts
随时怀疑
EDIT:编辑:
If else to be like this如果要这样
const styleGenerator = (darkMode = false, filterState = "A") => {
if (darkMode) {
if (filterState === 'A') {
return styles.activeButtonDark
}
if (filterState === 'B') {
return styles.stylesNew
}
return styles.buttonDark
} else {
if (filterState === 'A') {
return styles.activeButton
}
if (filterState === 'B') {
return styles.newStyle
}
return styles.button
}
}
style = {
styleGenerator(darkMode, filterState)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.