zoukankan      html  css  js  c++  java
  • 带你从零学ReactNative开发跨平台App开发(十一)

     ReactNative跨平台开发系列教程:

    带你从零学ReactNative开发跨平台App开发(一)

    带你从零学ReactNative开发跨平台App开发(二)

    带你从零学ReactNative开发跨平台App开发(三)

    带你从零学ReactNative开发跨平台App开发(四)

    带你从零学ReactNative开发跨平台App开发(五)

    带你从零学ReactNative开发跨平台App开发(六)

    带你从零学ReactNative开发跨平台App开发(七)

    hot:更多>>

     贴一个交流群的二维码,欢迎加入:

    贴一个交流群二维码,欢迎加入

    上篇说要来点真干货,由于接口没有整理好,我打算整理好接口直接部署到服务器上,这样大家可以一起使用,很遗憾,还没有整理好,不过,今天依然来点干货,只不过不是太干!

    废话不多说,开始撸码,你准备好了吗?


    这篇主要利用expo上集成的sqllite数据,以及一些缓存操作,做一个简单类型的备忘录!

    主要用到依赖有

        "expo": "^23.0.4",
        "pubsub-js": "^1.5.7",
        "react": "16.0.0",
        "react-native": "0.50.3",
        "react-navigation": "^1.0.0-beta.22"

    该项目源代码,全部推到github,点击这里获取!

    这个demo虽然小,但是灵活的控制了数据流。希望大家可以有所收获。

    犹豫本项目用到了SqlLite,在此我想喷一些那些搞移动端之想着掉接口的屌丝们!

    下面简单介绍一些代码:(能把 这写代码看透彻的人,我给你点赞!)

    //import liraries
    import React, { Component } from 'react';
    import {
        View,
        Text,
        StyleSheet,
        TouchableOpacity,
        ListView,
    } from 'react-native';
    import PubSub from 'pubsub-js';
    import MainItem from './MainItem';
    import TodoManager from '../DataServer/TodoManager';
    import AddTodo from './AddTodo';
    import Footer from '../Component/Footer';
    // create a component
    class MainView extends Component {
        static navigationOptions = {
            title: '备忘录',
            headerStyle: ({
                backgroundColor: "#0EABE8",
                elevation: 0,
            }),
            headerTitleStyle: ({
                alignSelf: 'center'
            }),
            headerLeft: (
                <TouchableOpacity onPress={() => {
                    PubSub.publish('all');
                }}>
                    <Text>全选</Text>
                </TouchableOpacity>
            ),
            headerRight: (
                <TouchableOpacity onPress={() => {
                    PubSub.publish('add');
                }}>
                    <Text>添加</Text>
                </TouchableOpacity>
            )
        }
        componentDidMount() {
            PubSub.subscribe('all', () => {
                TodoManager.selectAll();
            });
            PubSub.subscribe('add', () => {
                this.props.navigation.navigate('AddTodo');
            });
            TodoManager.setListener((todo) => {
                this.setState({
                    ds: this.state.ds.cloneWithRows(todo),
                });
            });
            TodoManager.setFinishListener((total) => {
                this.setState({
                    selectCount: total,
                });
            });
            TodoManager.getTodoInfo();
    
        }
        constructor(props) {
            super(props);
            const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) =>  r1 !== r2  });
            this.state = {
                ds: ds.cloneWithRows([]),
                isSelect: false,
                selectCount: 0,
            }
        }
        render() {
            return (
                <View style={styles.container}>
                    <ListView
                        dataSource={this.state.ds}
                        renderRow={(rowData) => {
                            console.log('===========rowData=========================');
                            console.log(rowData);
                            console.log('====================================');
                            return (
                                <View>
                                    <MainItem
                                        {...rowData}
                                        clickSelect={(id) => {
                                            console.log('====================================');
                                            console.log('点击了id' + id);
                                            console.log('====================================');
                                            TodoManager.singleSelect(id);
                                        }} />
                                    <Text>{rowData.finish}</Text>
                                </View>
    
                            );
                        }}
                        enableEmptySections={true}
                    />
    
                    <Footer selectCount={this.state.selectCount} />
                </View>
            );
        }
    }
    
    // define your styles
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#fff',
        },
    });
    
    //make this component available to the app
    export default MainView;

    关于操作SqlLite的Manager

    import { SQLite } from 'expo';
    class TodoManager {
        constructor() {
            this.db = SQLite.openDatabase('todoDB4');
            this.db.transaction((tx) => {
                const sql = "create table 'main'.'todo' ('id' integer not null primary key autoincrement,'name' text,'content' text,'finish' integer)";
                tx.executeSql(sql, null, (tx, result) => {
                    console.log('====================================');
                    console.log('创建表成功');
                    console.log('====================================');
                }, (tx, error) => {
                    console.log('====================================');
                    console.log('创建表失败' + error);
                    console.log('====================================');
                });
            });
        }
    
        setListener(listener) {
            this.listener = listener;
        }
    
        setFinishListener(listener) {
            this.finishListener = listener;
        }
    
        getTodoInfo(callBack) {
            console.log('====================================');
            console.log('bbbbb');
            console.log('====================================');
            this.db.transaction((tx) => {
                const sql = 'select * from todo';
                tx.executeSql(sql, null, (tx, result) => {
                    const todos = result.rows._array;
                    console.log('=============todostodos=======================');
                    console.log(todos);
                    console.log('====================================');
                    
                    //监听选中与否的变量变化
                    let selectCount = 0;
                    todos.map((value) => {
                        if (value.finish == 1) {
                            selectCount++;
                        }
                    });
                    //巧妙思路的变化
                    if (callBack) {
                        callBack(todos);
                    }
                    if (this.listener) {
                        console.log('====================================');
                        console.log('this.listener');
                        console.log('====================================');
                        this.listener(todos);
                    }
                    //回传过去
                    this.finishListener(selectCount);
                }, (tx, error) => {
                    console.log('====================================');
                    console.log('查询失败' + error);
                    console.log('====================================');
                    //巧妙思路的变化
                    if (callBack) {
                        callBack([]);
                    }
                    if (this.listener) {
                        this.listener([]);
                    }
                });
            });
        }
    
        addTodoInfo(info, callBack) {
            this.db.transaction((tx) => {
                const sql = `insert into todo(name,content,finish) values('${info.name}','${info.content}',0)`;
                tx.executeSql(sql, null, (tx, result) => {
                    console.log('====================================');
                    console.log('添加成功');
                    console.log('====================================');
                    this.getTodoInfo();
                    if (callBack) {
                        callBack(true);
                    }
    
                }, (tx, error) => {
                    console.log('====================================');
                    console.log('添加失败' + error);
                    console.log('====================================');
                    if (callBack) {
                        callBack(false);
                    }
                });
            });
        }
    
        delTodoInfo() {
            // this.db.transaction((tx) => {
            //     const ids = info.id.join(',');
            //     const sql = `delete from todo where id in (${ids})`;
            //     tx.executeSql(sql, null, (tx, result) => {
            //         console.log('====================================');
            //         console.log('删除成功');
            //         console.log('====================================');
            //         if (callBack) {
            //             callBack(true);
            //         }
            //         this.getTodoInfo();
            //     }, (tx, error) => {
            //         console.log('====================================');
            //         console.log('删除失败' + error);
            //         console.log('====================================');
            //         if (callBack) {
            //             callBack(false);
            //         }
            //     });
    
            // });
            this.db.transaction((tx) => {
                const sql = 'delete from todo where finish = 1';
                tx.executeSql(sql, null, (tx, resultSet) => {
                    console.log('删除成功');
                    this.getTodoInfo();
                })
            })
        }
    
        //全选
        selectAll() {
            this.db.transaction((tx) => {
                const sql = 'select * from todo';
                tx.executeSql(sql, null, (tx, result) => {
                    const array = result.rows._array;
                    let length = array.length;
                    let slength = 0;
                    array.map((value, key) => {
                        if (value.finish == 1) {
                            slength++;
                        }
                    });
                    if (slength == length) {
                        //取消全选
                        const sql = 'update todo set finish=0';
                        tx.executeSql(sql, null, (tx, resultSet) => {
                            if (resultSet) {
                                this.getTodoInfo();
                            }
                        }, (tx, error) => {
                            console.log('====================================');
                            console.log('取消全选失败' + error);
                            console.log('====================================');
                        });
    
                    } else {
                        //全选
                        const sql = 'update todo set finish=1';
                        tx.executeSql(sql, null, (tx, resultSet) => {
                            if (resultSet) {
                                this.getTodoInfo();
                            }
                        }, (tx, error) => {
                            console.log('====================================');
                            console.log('全选失败' + error);
                            console.log('====================================');
                        });
                    }
    
                }, (tx, error) => {
                    console.log('====================================');
                    console.log('全选失败' + error);
                    console.log('====================================');
                });
            });
        }
    
        //单选
        singleSelect(id) {
            //先根据传过来的id查询一下
            this.db.transaction((tx) => {
                const sql = `select * from todo where id=${id}`;
                tx.executeSql(sql, null, (tx, resultSet) => {
                    //修改其状态
                    const todo = resultSet.rows._array[0];
                    const finish = todo.finish ? 0 : 1;//修改
                    const sql = `update todo set finish=${finish} where id=${id}`;
                    tx.executeSql(sql, null, (tx, resultSet) => {
                        console.log('==============aaaa======================');
                        console.log('aaaa');
                        console.log('====================================');
                        this.getTodoInfo();
                    })
                }, (tx, error) => {
                    console.log('====================================');
                    console.log('单选失败' + error);
                    console.log('====================================');
                });
            });
    
        }
    
    }
    export default new TodoManager();

    细节就不详细介绍了,代码github上自己好好研究!


    后续文章持续更新,敬请期待!

    文章为作者原创,转载请注明出处。

  • 相关阅读:
    Jmeter +Maven+jenkins+eclipse 接口自动化测试
    感知机
    第1章 统计学习方法概论
    java jdk安装 以及myeclipse安装
    邻接表
    c语言 文件写入和读取
    c++ string
    线程-run和start
    Transfer learning across two sentiment classes using deep learning
    层次遍历
  • 原文地址:https://www.cnblogs.com/gdsblog/p/8128113.html
Copyright © 2011-2022 走看看