Here's a concrete example of a React Native app that allows users to create and save notes:
First, let's create a new React Native project using the Expo CLI:
bashexpo init MyNotesApp
cd MyNotesApp
Next, we'll install some dependencies for handling user input and storing data:
javanpm install @react-native-async-storage/async-storage react-native-elements react-native-vector-icons
We'll also install the react-navigation
library for creating navigation between screens:
javanpm install @react-navigation/native @react-navigation/stack
Now, let's create a Note
component that displays a single note:
phpimport React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const Note = ({ note }) => {
return (
<View style={styles.note}>
<Text style={styles.title}>{note.title}</Text>
<Text style={styles.body}>{note.body}</Text>
</View>
);
};
const styles = StyleSheet.create({
note: {
backgroundColor: 'white',
padding: 10,
margin: 5,
borderRadius: 5,
shadowColor: 'black',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
shadowRadius: 2,
elevation: 2,
},
title: {
fontWeight: 'bold',
marginBottom: 5,
},
body: {},
});
export default Note;
Next, we'll create a NotesList
component that displays a list of notes:
javascriptimport React from 'react';
import { FlatList } from 'react-native';
import Note from './Note';
const NotesList = ({ notes, onNotePress }) => {
return (
<FlatList
data={notes}
keyExtractor={(note) => note.id.toString()}
renderItem={({ item }) => (
<Note note={item} onPress={() => onNotePress(item)} />
)}
/>
);
};
export default NotesList;
Now, let's create a NewNote
component that allows users to create a new note:
javascriptimport React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import { Icon } from 'react-native-elements';
import { v4 as uuidv4 } from 'uuid';
const NewNote = ({ onSaveNote }) => {
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const handleSaveNote = () => {
const id = uuidv4();
const note = { id, title, body };
onSaveNote(note);
};
return (
<View style={styles.container}>
<Icon name="edit" type="material" />
<TextInput
placeholder="Title"
style={styles.titleInput}
value={title}
onChangeText={(text) => setTitle(text)}
/>
<TextInput
placeholder="Body"
style={styles.bodyInput}
value={body}
onChangeText={(text) => setBody(text)}
multiline={true}
numberOfLines={4}
/>
<Button title="Save" onPress={handleSaveNote} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
alignItems: 'center',
justifyContent: 'center',
},
titleInput: {
width: '100%',
fontSize: 20,
fontWeight: 'bold',
marginBottom: 10,
textAlign: 'center',
},
No comments:
Post a Comment
Thanks for your comments