皆さんこんにちは個別指導塾コミット塾長、AWESOME開発担当の船津です。
今回はクライアントサイドで用いられるモバイルデータベースの筆頭である、realmを使ってみます。
エキサイト翻訳、amazonなど有名どころも使っていると噂のすごいやつです。
SQLiteよりも軽くて早いとか!?
詳しくは公式サイトをどうぞ
https://realm.io/docs/react-native/latest/#writes
目次
細かいことはわからないですが、早速試してみましょう
- 今回は猫の名前を入れるとリストビューで表示される、というものをつくります。
- 今回は猫の名前以外のパラメータは固定です。
- このあたりは次回フォームを導入して解消してみましょう。
と、その前に、以下のコマンドを実行してreact nativeのプロジェクトを作成し、realmをインストールして下さい。
ract-native init realmTest
cd realmTest
npm install realm --save
今回はindex.ios.jsだけ編集します。
- ListViewはrealmからインポートしたほうが早いとか
- 猫の名前を入力するとListViewに表示されます
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
} from 'react-native'
import Realm from 'realm'
import { ListView } from 'realm/react-native';
const CatSchema = {
name: 'Cat',
properties: {
name: 'string',
birthplace: 'string',
sex: 'string',
type: 'string',
}
}
let realm = new Realm({schema: [CatSchema] })
class realmTest extends Component {
constructor(props) {
super(props)
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
let src = realm.objects('Cat')
this.state = ({
dataSource: ds.cloneWithRows(src),
data:src
});
}
_updateData(){
this.setState({
dataSource: this.state.dataSource.cloneWithRows(this.state.data)
});
}
_renderRow(rowData) {
return (
<View style={{marginTop:10}}>
<Text>名前:{rowData.name}</Text>
<Text>出生地:{rowData.birthplace}</Text>
<Text>性別:{rowData.sex}</Text>
<Text>品種:{rowData.type}</Text>
</View>
)
}
render() {
return (
<View style={styles.container}>
<View style={styles.input}>
<Text style={styles.welcome}>
猫ちゃんの名前を入れてね
</Text>
<TextInput
style={{
height: 30,
width: 150,
borderWidth: 1,
borderColor: "rgba(0,0,0,0.5)",
marginTop: 10,
}}
placeholder={'Type here'}
placeholderTextColor={"rgba(198,198,204,1)"}
onChangeText={(text) => {this.setState({text})}}
onSubmitEditing={() => {
realm.write(() => {
realm.create('Cat', {
name: this.state.text,
birthplace: 'kakogawa',
sex: 'male',
type: 'American Shorthair',
})
})
this.setState({text: ''})
this._updateData()
}}
value={(this.state && this.state.text) || ''}
/>
</View>
<View style={styles.list}>
<ListView
enableEmptySections={true}
dataSource={this.state.dataSource}
renderRow={this._renderRow}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
input: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
list: {
flex: 4,
justifyContent: 'center',
}
});
AppRegistry.registerComponent('realmTest', () => realmTest);
完成するとこんな感じだよ

次回は
前回のTodoリストと同様に選んだものを消したり、フラグ管理したりしてみましょう。



