Прежде всего бегом -›
npx react-native init myToDoapp
Чтобы использовать хранилище, мы будем использовать этот модуль https://react-native-async-storage.github.io/async-storage/docs/install/.
npm install @react-native-community/async-storage
Бегать ->
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view npm install @react-navigation/native @react-navigation/stack
Чтобы использовать реагирующую навигацию
посетите https://reactnavigation.org/docs/getting-started/ для получения дополнительной информации.
Теперь установите родную базу.
npm install native-base
Установить шортид
npm install shortid
Проверьте свой package.json на наличие этих зависимостей.
Создайте новую папку Screens и создайте новые файлы «ToDoHome.js» и «Add.js».
В App.js добавить-›
import 'react-native-gesture-handler'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import React from 'react' import Add from './Screens/Add'; import ToDoHome from './Screens/ToDoHome' const Stack = createStackNavigator(); const App=()=>{ return( <NavigationContainer> <Stack.Navigator initialRouteName="Home"> <Stack.Screen name="Home" component={ToDoHome} options={{ headerStyle:{ backgroundColor:"gray" }, title:"To Do App", headerTitleAlign:'center', headerTitleStyle:{ color:"#FFFFFF" } }} > </Stack.Screen> <Stack.Screen name="AddToDo" component={Add}> </Stack.Screen> </Stack.Navigator> </NavigationContainer> ) } export default App;
В ToDoHome.js добавить-›
import React,{ useState,useEffect } from 'react' import { Fab,Icon, Left, ListItem,List, Right, Body, CheckBox} from 'native-base'; import {ScrollView,Text,StyleSheet} from 'react-native' import AsyncStorage from '@react-native-community/async-storage' import { useIsFocused } from '@react-navigation/core'; const ToDoHome=({navigation,route})=>{ const [listofToDo,setListofToDo] = useState([]) const focus = useIsFocused() const getData = async()=>{ const storedvalues = await AsyncStorage.getItem('@todoitem') const readableForm = await JSON.parse(storedvalues) setListofToDo(readableForm) console.log("========================================================"); console.log(listofToDo.length); } const handleDelete = async(id)=>{ const anotherList = listofToDo.filter((list)=>list.id!==id) await AsyncStorage.setItem('@todoitem',JSON.stringify(anotherList)) setListofToDo(anotherList) } const isitMarked=async(id)=>{ const newList = listofToDo.map((item)=>{ if(item.id==id){ item.isDone= !item.isDone } return item }) await AsyncStorage.setItem('@todoitem',JSON.stringify(newList)) setListofToDo(newList) } useEffect(()=>{ getData() },[focus]) return( <ScrollView contentContainerStyle={styles.scroolview}> { listofToDo.length ==0?(<Text style={{ backgroundColor:"black", color:"white", textAlign:'center' }} > Please Add An item </Text>):( <List> { listofToDo.map((todo)=>( <ListItem key={todo.id} style={styles.listItem}> <Left> <Icon style={styles.actionButton} onPress={()=>handleDelete(todo.id)} active name="trash"/> <Icon style={styles.actionButton} active name="wifi"/> </Left> <Body> <Text>{todo.task}</Text> <Text note> {todo.details}</Text> </Body> <Right> <CheckBox checked={todo.isDone} onPress={()=>isitMarked(todo.id)} ></CheckBox> </Right> </ListItem> )) } </List> ) } <Fab style={{backgroundColor:"#507FFF"}} position="bottomRight" active onPress={()=>navigation.navigate("AddToDo")} > <Icon name="add"/> </Fab> </ScrollView> ) } export default ToDoHome; const styles=StyleSheet.create({ scroolview:{ flex:1, backgroundColor:"gray" }, actionButton: { marginLeft: 5, justifyContent:'space-between' }, listItem: { marginLeft: 0, marginBottom: 3, backgroundColor:"#FFFFFF", }, })
Add.js
import { Text,Container,Content,Form,Input,Item, Button } from 'native-base'; import React from 'react' import { useState } from 'react'; import {StyleSheet} from 'react-native' import AsyncStorage from '@react-native-community/async-storage' import shortid from 'shortid'; const Add=({navigation,route})=>{ const [task,setTask] = useState('') const [details,setDetails] = useState('') const handleInput=async()=>{ try { if(!task || !details){ return alert("Please Enter valid values") } const taskToAdd = { id:shortid.generate(), task:task, details:details, isDone:false } const storedToDo = await AsyncStorage.getItem('@todoitem') const previousList =await JSON.parse(storedToDo) if(!previousList){ const newList = [taskToAdd] await AsyncStorage.setItem('@todoitem',JSON.stringify(newList)) } else{ previousList.push(taskToAdd) await AsyncStorage.setItem('@todoitem',JSON.stringify(previousList)) } navigation.navigate('Home') } catch (error) { console.log(error); } } return( <Container style={styles.container}> <Content> <Form> <Item rounded style={styles.items} > <Input placeholder="Enter your work" value={task} onChangeText={(event)=>setTask(event)}/> </Item> <Item rounded style={styles.items}> <Input placeholder="additional" value={details} onChangeText={(event)=>setDetails(event)}/> </Item> <Button rounded success onPress={handleInput} style={{alignSelf:'center',paddingHorizontal:25}} > <Text>Add</Text> </Button> </Form> </Content> </Container> ) } export default Add; const styles = StyleSheet.create({ container:{ flex:1, padding:10, justifyContent:'space-between', marginBottom:10 }, items:{ marginBottom:15, paddingStart:5 } })
Теперь беги
npx react-native start
и
npx react-native run-android
Выход->
Посетите -› https://github.com/49paunilay/React-Native-ToDo-App/tree/main/myToDoApp для файлов кода