I'm learning react-native, as a beginner, i learn by search random project on github and find what weird and not understand, then learn from it, today i see some code of a dude ( i don't remember his name) but it looke like this
{isTrue && (
<TouchableOpacity onPress={reset && reset}> ===>they are the same function
<Text>Reset</Text>
</TouchableOpacity>
)}
Why we have something like this? Why don't use reset directly, this guy use &&
Please help me on this, i'm so confuse about this
CodePudding user response:
I expect the code rather looks like that:
<TouchableOpacity onPress={() => {reset && reset()}}>
<Text>Reset</Text>
</TouchableOpacity>
reset && reset() // && shorthand for
if(reset) {
reset()
}
AFAIK there a no relevant different between
<TouchableOpacity onPress={reset && reset}}>
<Text>Reset</Text>
</TouchableOpacity>
and
<TouchableOpacity onPress={reset}}>
<Text>Reset</Text>
</TouchableOpacity>
reset && reset
will ensure that reset is always undefined when reset is falsy. Otherwise reset could be false,0,'', null or NaN.
But i think that has no effect but meet the TypeScript definition onPress definition which is undefined or function onPress?: () => void;