如何在React Native中使用三元运算符控制清空按钮的显隐
实现方案
你可以直接通过待办列表的长度控制清空按钮的显隐,不需要额外维护独立的显隐状态,修改成本很低:
核心修改说明
- 移除冗余的
show状态变量,直接用items.length > 0作为按钮渲染的判断条件:items本身就是响应式状态,长度变化会自动触发组件重渲染,无需手动同步显隐状态 - 修正原有错误的条件渲染逻辑,仅当待办列表存在内容时渲染清空按钮
修改后完整代码
import React from 'react' import { StyleSheet, Text, View, TextInput, Button, Alert, ScrollView } from 'react-native'; import Header from './Components/Header'; import { AntDesign } from '@expo/vector-icons'; const App = () => { const [text, setText] = React.useState(""); const [items, setItems] = React.useState([]) // Add a todo const addTodo = () => { if (text == "") { alert("Please Enter Todo"); } else { setItems([...items, text]); setText(''); } } // Delete a todo const deleteItem = (id) => { const updatedItems = items.filter((elem, ind) => { return ind != id; }) setItems(updatedItems); } // Clear all todo const clearAllItems = () => { setItems([]); } return ( <ScrollView> <View> <Header /> <TextInput style={styles.input} value={text} onChangeText={(e) => setText(e)} /> <Button title="Add +" onPress={addTodo} /> <View style={styles.list}> {items.map((elem, ind) => { return ( <View key={ind} style={styles.listitem}> <Text style={styles.item}>{elem}</Text> <Text style={styles.icon} onPress={() => deleteItem(ind)}><AntDesign name="delete" size={24} color="black" /></Text> </View> ) })} </View> {/* 仅当待办列表长度大于0时渲染清空按钮 */} {items.length > 0 && <Button title="Clear" onPress={clearAllItems} />} </View> </ScrollView> ) } export default App const styles = StyleSheet.create({ list: { marginTop: 20, padding: 50, }, item: { display: 'flex', flexDirection: 'column', padding: 10, marginTop: 10, borderWidth: 1, borderStyle: 'dashed', borderColor: 'gray', textAlign: 'center', backgroundColor: '#5ed9db', fontWeight: 'bold', color: 'black', fontSize: 20, width: 280 }, input: { height: 40, margin: 12, borderWidth: 1, padding: 10, }, listitem: { flexDirection: 'row', justifyContent: 'space-between' }, icon: { marginTop: 10, borderWidth: 1, borderColor: 'black', backgroundColor: '#5edbb3', width: 50, fontSize: 20, fontWeight: 'bold', alignItems: 'center', textAlign: 'center', padding: 10 } })
内容的提问来源于stack exchange,提问作者Monu Patil
相关产品推荐
相关产品推荐

