react native:如何根据条件显示或隐藏TouchableOpacity ?



如何根据条件显示或隐藏TouchableOpacity ?如何根据条件查看或隐藏touchableacity只有当Sampling_Method_Description字段不为空,则应该显示TouchableOpacity,否则不显示。

<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'red',
left: 120,
top: 7,
}}
onPress={() => {
console.log('EYE PRESSED!!')
}}
>
<MaterialIcons
size={40}
name='visibility' 
/>
</TouchableOpacity>

您可以在JSX块中使用三元运算符,如下所示:


return (
<View>
{yourConditionIsTrue?
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'red',
left: 120,
top: 7,
}}
onPress={() => {
console.log('EYE PRESSED!!')
}}
>
<MaterialIcons
size={40}
name='visibility' 
/>
</TouchableOpacity>
:
null }
</View>
)
import React, {useState} from "react";
import { View } from "react-native";
Example = () => {
const [showButton, setshowButton] = useState(false);
const renderButton = () => {
return showButton ? (
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: "black",
borderWidth: 2,
alignItems: "center",
justifyContent: "center",
backgroundColor: "red",
left: 120,
top: 7,
}}
onPress={() => {
console.log("EYE PRESSED!!");
}}>
<MaterialIcons size={40} name="visibility" />
</TouchableOpacity>
) : null;
};
return <View>{renderButton()}</View>;
};

您可以简单地使用&&运算符:

{Sampling_Method_Description && 
<TouchableOpacity
//other props
//...
//...
/>}

最新更新