クラス型コンポーネントだと下記
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import React from 'react';
import { TextInput } from 'react-native';
import {collection, addDoc,getFirestore } from 'firebase/firestore';
import {initializeApp, getApps} from 'firebase/app';
const firebaseConfig = {
apiKey: "AII",
authDomain: "app.com",
projectId: "s",
storageBucket: "sam",
messagingSenderId: "98265",
appId: "108"
};
if(getApps().length == 0){
const app = initializeApp(firebaseConfig);
}
const db = getFirestore();
class Contents extends React.Component{
constructor(props){
super(props);
this.state = {
theme:"",
name:""
}
this.addItem = this.addItem.bind(this);
}
addItem(){
const theme = this.state.theme;
const name = this.state.name;
const itemsCollection = collection(db, 'items');
addDoc(itemsCollection,{theme, name});
}
render(){
return(
<View>
<Text>タイトル</Text>
<TextInput
onChangeText={text => this.setState({theme:text})}
style={{borderWidth:1}}
/>
<Text>名前</Text>
<TextInput
onChangeText={text => this.setState({name:text})}
style={{borderWidth:1}}
/>
<Button
title="追加"
onPress={this.addItem}
/>
</View>
)
}
}
export default function App() {
return (
<View style={styles.container}>
<Contents/>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
機能型コンポーネントに変換するとこうである。
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import React from 'react';
import { TextInput } from 'react-native';
import {collection, addDoc,getFirestore } from 'firebase/firestore';
import {initializeApp, getApps} from 'firebase/app';
import {useState} from 'react';
const firebaseConfig = {
apiKey: "AIzaSyCeLBvc_bkFBEykWpE_slK9FW0UvkOAWNI",
authDomain: "sample15-cacb9.firebaseapp.com",
projectId: "sample15-cacb9",
storageBucket: "sample15-cacb9.appspot.com",
messagingSenderId: "982678183065",
appId: "1:982678183065:web:b2b1de35340dd9b03f2c08"
};
if(getApps().length == 0){
const app = initializeApp(firebaseConfig);
}
const db = getFirestore();
function Contents(){
const [theme, setTheme] = useState("");
const [name, setName] = useState("");
const addItem =() =>{
const itemsCollection = collection(db, 'items');
addDoc(itemsCollection,{theme, name});
}
return(
<View>
<Text>タイトル</Text>
<TextInput
onChangeText={text => setTheme(text)}
style={{borderWidth:1}}
/>
<Text>名前</Text>
<TextInput
onChangeText={text => this.setName(text)}
style={{borderWidth:1}}
/>
<Button
title="追加"
onPress={this.addItem}
/>
</View>
)
}
export default function App() {
return (
<View style={styles.container}>
<Contents/>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});