【发布时间】:2021-09-13 15:59:31
【问题描述】:
我是 React native 的新手,我在这个应用程序中创建了一个简单的 todo 应用程序,我添加了一个清除按钮,我的问题是,当我添加 todo 时显示清除按钮,否则我不想要它。如果您有任何疑问,请随时提出任何问题。
这是我简单的添加待办事项代码,在这个应用程序中我使用了函数组件
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([])
const [show, setShow] = React.useState(false);
// 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>
{
show ? items : <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
}
})
【问题讨论】:
-
初始化后
setShow在哪里使用过? -
您需要一个平面列表来显示您的项目或映射数组以返回所需的组件
标签: css react-native react-hooks