我有“视图”->“按钮”。我想在单击按钮时从屏幕上删除此视图。是否可以删除视图组件,或者我们应该隐藏它吗?或者我们应该将视图高度设置为0?
如有任何建议,我们将不胜感激。提前谢谢?
由于我是 React Native 的新手,所以我无法做到这一点。我想设置一些道具来查看,例如模态的可见道具。但我不知道 View 组件的 prop 名称。
您需要确定“删除”
View
在您的应用程序上下文中意味着什么。您的选择是:
View
。这完全删除了不应该渲染的 View
并且它不会占用任何空间。const [show, setShow] = useState(true);
return (
<View style={styles.container}>
{show && (
<View>
<Text>Test by not rendering</Text>
</View>
)}
<Button onPress={() => setShow(!show)} title="Toggle Show" />
</View>
View
透明。这将隐藏您的视图,但它仍然会占用相同的空间。const [show, setShow] = useState(true);
return (
<View style={styles.container}>
<View style={{ opacity: show ? 1 : 0 }}>
<Text>Test by setting opacity: 0</Text>
</View>
<Button onPress={() => setShow(!show)} title="Toggle Show" />
</View>
width
或 height
设置为 0,或两者都设置!const [show, setShow] = useState(true);
return (
<View style={styles.container}>
<View style={{ height: show ? 100 : 0 }}>
<Text>Test by collapsing height</Text>
</View>
<Button onPress={() => setShow(!show)} title="Toggle Show" />
</View>
这些选项都在某种程度上起作用,但这又取决于您的应用程序需要。也就是说,选项 1 在概念上是最简单的,避免了潜在的副作用,并且对于许多用途来说可能更高效。