react_native 项目实战 (4) 自定义分类 使用 CheckBox 以及 数据存储asyncStorage

前端之家收集整理的这篇文章主要介绍了react_native 项目实战 (4) 自定义分类 使用 CheckBox 以及 数据存储asyncStorage前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用CheckBox

先看使用CheckBox效果

引入CheckBox 第三方复选框react-native-check-Box

npm install react-native-check-Box –save //两个横杠

leftText 的Text 大写.又被坑了一次

CheckBox
http://www.searu.org/39207.html

遇到的问题

1,点击后就隐藏了 解决: 更新react-native-check-Box 到最新的 就好了 吐血这个问题

我开始想自己写的 但想着自己写肯定费时费力 不甘心 各种找资料 还是找到了

"react-native-check-Box": "^2.0.2",

npm install react-native-check-Box –save 用这个命令 别用github上面的那个readmi说的命令

真的坑啊

2,checkBox 没有勾选 解决: 原因isChecked Checked 我的c是小写 ..

其他的难点就是关于算法的问题了 主要是这几个CheckBox如何布局 大致说下把:

@H_301_34@
  • 定义一个views数组 里面装了所有的CheckBox
  • 每一行我包裹起来 包裹了两个checkBox 然后用views数组给push进去
  • 需要留出最后一样 通过判断奇数偶数 再把最后一行添加进去
  • 具体看代码

     
     

    AsyncStorage使用 进行数据存取

    引用

    import {
        AppRegistry,StyleSheet,Text,View,Image,TouchableOpacity,AsyncStorage
    } from 'react-native';

    通过 setItem方法保存数据 key- value 形式

    AsyncStorage.setItem('custom_key',JSON.stringify(this.state.data))
                .then(() => this.refs.toast.show("保存成功"));

    获取 getItem 方法获取数据

    AsyncStorage.getItem('custom_key')
                .then(value => {
                    //有用户数据,选中该选中CheckBox
                    if (value !== null) {
                        // console.log(JSON.parse(value));
                        this.setState({data: JSON.parse(value)});
                    } else {
                        this.setState({
                            data: [{name: 'Android',checked: true},{name: 'IOS',{name: 'React Native',{name: 'Java',{name: 'JS',checked: true}]
                        });
                    }
                });

    下面上完成的代码

    /**
     * Created by liuml on 2017/9/17.
     */
    import React,{Component} from 'react';
    import {
        AppRegistry,AsyncStorage,TouchableOpacity
    } from 'react-native';
    /**
     * 自定义分类页面
     */
    import NavigationBar from '../compont/NavigationBar';
    import CheckBox from 'react-native-check-Box';
    import Toast from "react-native-easy-toast"
    export default class CustomKeyPage extends Component {
    
        // 构造
        constructor(props) {
            super(props);
            // 初始状态
            this.state = {
                data: [{name: 'android',checked: true},{name: 'IOS',checked: false}]
            };
        }
    
        handleBack = () => {
            this.props.navigation.goBack();
        }
        getLeftBtn = () => {
            return <View style={{flexDirection: 'row',alignItems: 'center'}}>
                <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={this.handleBack}>
                    <Image source={require('../../res/images/ic_arrow_back_white_36pt.png')}
                           style={{width: 24,height: 24}}/>
                </TouchableOpacity>
            </View>;
        }
    
    
        getRightBtn = () => {
            return <View style={{flexDirection: 'row',alignItems: 'center'}}>
                <TouchableOpacity
                    onPress={this.handleSave}
                    activeOpacity={0.7}>
                    <View style={{marginRight: 10}}>
                        <Text style={{fontSize: 16,color: '#FFF'}}>保存</Text>
                    </View>
                </TouchableOpacity>
            </View>;
        }
    
        //保存
        handleSave = () => {
            //http://lib.csdn.net/article/reactnative/43540   JSON.stringify 字符串转JSON
            //AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统
            AsyncStorage.setItem('custom_key',JSON.stringify(this.state.data))
                .then(() => this.refs.toast.show("保存成功")); // console.log(JSON.stringify(this.state.data)); } //CheckBox 点击 有个疑问为什么在这里设置值就可以不用setState就改变itemchecked,因为是这样调用()=>this.handlerCBClick(item)
        handleClick = (item) => {
            // console.log("之前 " + item.checked);
            item.checked = !item.checked;
            // console.log("之后 " + item.checked);
        }
        //渲染CheckBox  这里item就是一个对象
        renderCheckBox = (item) => {
            // console.log(item);
            // console.log(item.name + ',' + item.checked);
            var leftText = item.name;
            return <CheckBox
                style={{flex: 1,padding: 10}}
                onClick={() => this.handleClick(item)}
                leftText={item.name}
                isChecked={item.checked}
                unCheckedImage={<Image source={require('../../res/images/ic_check_Box_outline_blank.png')}
                                       style={styles.checkBox}/>}
                checkedImage={<Image source={require('../../res/images/ic_check_Box.png')} style={styles.checkBox}/>}
            />
        }
    
        renderViews = () => {
            let len = this.state.data.length;
            var views = [];  //要绘制的所有多选框,装入views数组
            for (let i = 0,j = len - 2; i < j; i += 2) {
                views.push((
                    <View key={`@H_766_403@view_${i}`} style={{flexDirection: 'row'}}>
                        {this.renderCheckBox(this.state.data[i])}
                        {this.renderCheckBox(this.state.data[i + 1])}
                    </View>
                ));
            }
    
    
            //偶数个,剩下最后两个多选框
            //奇数个,剩下最后一个多选框
            views.push(
                <View key={`@H_766_403@view_${len - 1}`} style={{flexDirection: 'row'}}>
                    {len % 2 === 0 ? this.renderCheckBox(this.state.data[len - 2]) :
                        <View style={{flex: 1,padding: 10}}></View>}
                    {this.renderCheckBox(this.state.data[len - 1])}
                </View>
            );
    
            return views;
        }
        componentDidMount = () => {
    
    
            this.loadData();
    
        }
    
        loadData = () => {
            //加载本地数据
            AsyncStorage.getItem('custom_key')
                .then(value => {
                    //用户数据,选中该选中CheckBox
                    if (value !== null) {
                        // console.log(JSON.parse(value));
                        this.setState({data: JSON.parse(value)});
                    } else {
                        this.setState({
                            data: [{name: 'Android',{name: 'React Native',{name: 'Java',{name: 'JS',checked: true}]
                        });
                    }
                });
    
            // console.log(this.state.data);
        }
    
        render() {
            return <View style={styles.container}>
                <NavigationBar
                    title="自定义分类"
                    rightButton={this.getRightBtn()}
                    leftButton={this.getLeftBtn()}/>
                <View style={{flexDirection: 'column'}}>
                    {this.renderViews()}
                </View>
                <Toast ref="toast"/>
            </View>
        }
    }
    
    const styles = StyleSheet.create({
    
        container: {
            flex: 1
        },checkBox: {
            tintColor: '#63B8FF'
        }
    
    });

    看看最终效果

    项目地址

    https://github.com/liudao01/ReactNativeProject

    猜你在找的React相关文章