技术文档参考地址https://realm.io/docs/javascript/latest/index.html
直接上步骤:
打开终端运行如下命令 cd (前提是已建项目) 2.添加依赖库 npminstall--saverealm 3.关联依赖库 rnpmlinkrealm 4.先看效果图(包含建表,增,删,改,查功能)
屏幕快照 2017-05-16 下午5.50.15.png
屏幕快照 2017-05-16 下午5.50.24.png
屏幕快照 2017-05-16 下午5.49.38.png
屏幕快照 2017-05-16 下午5.49.46.png
屏幕快照 2017-05-16 下午5.49.53.png
最后直接上代码:
import React, {Component} from 'react'
import {
View,
Text,
StyleSheet,
Button,
} from 'react-native'
const Realm = require('realm');
let realm;
//1. 主键primaryKey(string|int) 表名name 内容properties
const StudentsScheam = {
name: 'Student',
primaryKey: 'id',
properties: {
id: 'int',
s_sex: 'string',
s_name: 'string',
s_age: 'string',
phone: {
type: 'string',
default: '15980673237'
},//添加默认值的写法
}
};
export default class RealmTest extends Component {
constructor(props) {
super(props);
// 2.初始化 Realm
realm = new Realm({schema: [StudentsScheam]});
this.state = {
s_content: (Realm.defaultPath),
s_Length: 0,
}
}
componentDidMount() {
}
render() {
return (
{
realm.write(()=>{
realm.create('Student',{id:1,s_age:'10',s_name:'学生1',s_sex:'男'});
realm.create('Student',{id:2,s_age:'11',s_name:'学生2',s_sex:'女'});
realm.create('Student',{id:3,s_age:'12',s_name:'学生3',s_sex:'男'});
realm.create('Student',{id:4,s_age:'13',s_name:'学生4',s_sex:'女'});
realm.create('Student',{id:5,s_age:'14',s_name:'学生5',s_sex:'男'});
realm.create('Student',{id:6,s_age:'15',s_name:'学生6',s_sex:'女'});
alert('添加数据成功!');
})
}}
/>
{
let students = realm.objects('Student');
let student = students.filtered('id==3');
if (student.length > 0) {
realm.write(()=>{
realm.create('Student',{id:3,s_age:'33',s_name:'学生33'},true)
console.log(student[0].id+student[0].s_age+student[0].s_name+student[0].s_sex);
alert('id=3这条数据修改了!')
})
}else {
alert('该数据不存在');
}
}}
/>
{
realm.write(()=>{
let students = realm.objects('Student');
let student = students.filtered('id==3');
if (student.length > 0){
realm.delete(student);
alert('删除成功');
}else {
alert('该数据不存在');
}
})
}}
/>
{
realm.write(()=>{
let students = realm.objects('Student');
realm.delete(students);
alert('删除所有数据成功!');
})
}}
/>
{
let students = realm.objects('Student');
let student;
for (var index = 1;index 0){
console.warn(student[0].s_name+student[0].s_age+student[0].s_sex);
}else {
alert('查询不到数据')
}
}
}}
/>
{
let students = realm.objects('Student');
if (students.length > 0){
let student = students.filtered('id==4');
if (student){
console.warn(student[0].s_name+student[0].s_age+student[0].s_sex);
}
} else {
alert('未查询到id==4的数据')
}
}}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
marginTop:20,
},
});