您的位置:首页 > Web前端 > React

react native AsyncStorage的使用 单选,多选

2017-03-06 22:25 671 查看
 如果现在有一个需求,是要把用户的账号密码保存到本地,大家会怎么做的呢?如果在android中,我相信一大部分人会想到SharedPreferences,这是一个以键值对的形式进行存储的。那如果在react native中呢,有没有一个像SharedPreferences一样的轻量存储器呢?答案是有的---AsyncStorage。

  AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。这是官网上对它的介绍。可以知道,这个asyncstorage也是以键值对的形式进行存储数据的。

  那么问题来了,该怎么使用这个呢?官网上说并不推荐我们直接用这个asyncstorage,而是进行抽象封装以后在进行调用。首先看一看我在项目中的用法。

上代码:

1 import React, {
2     AsyncStorage
3 }from 'react-native';
4
5 class DeviceStorage {
6     /**
7      * 获取
8      * @param key
9      * @returns {Promise<T>|*|Promise.<TResult>}
10      */
11
12     static get(key) {
13         return AsyncStorage.getItem(key).then((value) => {
14             const jsonValue = JSON.parse(value);
15             return jsonValue;
16         });
17     }
18
19
20     /**
21      * 保存
22      * @param key
23      * @param value
24      * @returns {*}
25      */
26     static save(key, value) {
27         return AsyncStorage.setItem(key, JSON.stringify(value));
28     }
29
30
31     /**
32      * 更新
33      * @param key
34      * @param value
35      * @returns {Promise<T>|Promise.<TResult>}
36      */
37     static update(key, value) {
38         return DeviceStorage.get(key).then((item) => {
39             value = typeof value === 'string' ? value : Object.assign({}, item, value);
40             return AsyncStorage.setItem(key, JSON.stringify(value));
41         });
42     }
43
44
45     /**
46      * 更新
47      * @param key
48      * @returns {*}
49      */
50     static delete(key) {
51         return AsyncStorage.removeItem(key);
52     }
53 }
54
55 export default DeviceStorage;


可以看到asyncstorage中存在有更删改查这些方法,当然,上面是把asyncstorage进行了封装,在其他地方调用的时候就可以作为一个工具进行调用了。

调用方式:

1 //appHotSearchTagList就是当时保存的时候所保存的key,而tags就是保存的值
2
3 Storage.get('appHotSearchTagList').then((tags) => {
4             this.setState({
5                 tags: tags
6             })
7         });


这里我只是贴出了一种获取数据的方式,其实另外的更新,删除,保存,方式都是差不多。


react native RadioButton(单选按钮)

刚刚写完这个多选按钮,我觉得没有单选的话,总会觉得有一点点不爽,因为在项目中我也没有用到单选,所以我没有好好研究源码,所以我在Github上找了一下,发现有一个挺好的,简单,不花哨。

在Github上搜索这个

react-native-flexi-radio-button


下载好以后,就可以直接用了。

1 import React, { Component } from 'react';
2 import {
3   StyleSheet,
4   Text,
5   View
6 } from 'react-native';
7
8 import {RadioGroup, RadioButton} from 'react-native-flexi-radio-button'
9
10 class App extends Component{
11
12     constructor(){
13         super()
14         this.state = {
15             text: ''
16         }
17         this.onSelect = this.onSelect.bind(this)
18     }
19
20     onSelect(index, value){
21         this.setState({
22         text: `Selected index: ${index} , value: ${value}`
23         })
24     }
25
26     render(){
27         return(
28             <View style={styles.container}>
29                 <RadioGroup
30                     onSelect = {(index, value) => this.onSelect(index, value)}
31                 >
32                     <RadioButton value={'item1'} >
33                         <Text>This is item #1</Text>
34                     </RadioButton>
35
36                     <RadioButton value={'item2'}>
37                         <Text>This is item #2</Text>
38                     </RadioButton>
39
40                     <RadioButton value={'item3'}>
41                         <Text>This is item #3</Text>
42                     </RadioButton>
43
44                 </RadioGroup>
45
46                 <Text style={styles.text}>{this.state.text}</Text>
47             </View>
48         )
49     }
50 }
51
52 let styles = StyleSheet.create({
53     container: {
54         marginTop: 40,
55         padding: 20
56     },
57     text: {
58         padding: 10,
59         fontSize: 14,
60     },
61 })
62
63 module.exports = App



react native 多选按钮

在做项目的时候有一个需求,是可以选择多个条件的,特地在Github上找了一些案例,发现没有什么合适的,于是自己根据这些案例,改装一下,封装了一个合适自己的。先看我封装的代码。

1 import React, {Component} from 'react';
2 import {
3     StyleSheet,
4     View,
5     Image,
6     Text,
7     TouchableHighlight,
8 } from 'react-native'
9
10
11 export default class CheckBox extends Component {
12     constructor(props) {
13         super(props);
14         this.state = {
15             isChecked: this.props.isChecked,
16         }
17     }
18
19     /**
20      * propTypes是React内部提供的校验器,如果通过props传过的数据与之不匹配,则会抛出异常。
21      *
22      */
23     static propTypes = {
24         ...View.propTypes,
25         leftText: React.PropTypes.string,
26         leftTextView: React.PropTypes.element,
27         rightText: React.PropTypes.string,
28         leftTextStyle: Text.propTypes.style,
29         rightTextView: React.PropTypes.element,
30         rightTextStyle: Text.propTypes.style,
31         checkedImage: React.PropTypes.element,
32         unCheckedImage: React.PropTypes.element,
33         onClick: React.PropTypes.func.isRequired,
34         isChecked: React.PropTypes.bool
35
36     }
37
38
39     /**
40      * 如果没有通过props传过来数据,则默认的是这样
41      * @type
42      */
43     static defaultProps = {
44         isChecked: false,
45         leftTextStyle: {},
46         rightTextStyle: {}
47     }
48
49     /**
50      * 左边文字
51      */
52     _renderLeft() {
53         if (this.props.leftTextView) {
54             return this.props.leftTextView;
55         }
56
57         if (!this.props.leftText) {
58             return null;
59         }
60         return (
61             <Text style={[styles.leftText, this.props.leftTextStyle]}>{this.props.leftText}</Text>
62         )
63     }
64
65
66     /**
67      * 右边的文字
68      * @returns {*}
69      * @private
70      */
71     _renderRight() {
72         if (this.props.rightTextView) {
73             return this.props.rightTextView;
74         }
75         if (!this.props.rightText) {
76             return null;
77         }
78         return (
79             <Text style={[styles.rightText, this.props.rightTextStyle]}>{this.props.rightText}</Text>
80         )
81     }
82
83     /**
84      * 选中和为选中的图片按钮样式
85      * @returns {*}
86      * @private
87      */
88     _renderImage() {
89         if (this.state.isChecked) {
90             return this.props.checkedImage ? this.props.checkedImage : this.genCheckedImage();
91         } else {
92             return this.props.unCheckedImage ? this.props.unCheckedImage : this.genCheckedImage();
93         }
94     }
95
96     genCheckedImage() {
97         var source = this.state.isChecked ? require('./img/ic_check_box.png') : require('./img/ic_check_box_outline_blank.png');
98         return (
99             <Image source={source}/>
100         )
101     }
102
103
104     onClick() {
105         this.setState({
106             isChecked: !this.state.isChecked
107         })
108         this.props.onClick();
109     }
110
111     render() {
112         return (
113             <TouchableHighlight
114                 style={this.props.style}
115                 onPress={()=>this.onClick()}
116                 underlayColor='transparent'
117             >
118                 <View style={styles.container}>
119                     {this._renderLeft()}
120                     {this._renderImage()}
121                     {this._renderRight()}
122                 </View>
123             </TouchableHighlight>
124         )
125     }
126 }
127
128
129
130 const styles = StyleSheet.create({
131     container: {
132         flexDirection: 'row',
133         alignItems: 'center'
134     },
135     leftText: {
136         flex: 1,
137     },
138     rightText: {
139         flex: 1,
140         marginLeft: 10
141     }
142 })


基本上这些需要的属性都是通过props来传递过来的。

用法也比较简单:

1 import React, {Component} from 'react';
2 import {
3     StyleSheet,
4     ScrollView,
5     View,
6 } from 'react-native'
7
8 import keys from './keys.json'
9 import Toast from 'react-native-easy-toast'
10
11 export default class example extends Component {
12     constructor(props) {
13         super(props);
14         this.state = {
15             dataArray: []
16         }
17     }
18
19     componentDidMount() {
20         this.loadData();
21     }
22
23     loadData() {
24         this.setState({
25             dataArray: keys
26         })
27     }
28
29     onClick(data) {
30         data.checked = !data.checked;
31         let msg=data.checked? 'you checked ':'you unchecked '
32         this.toast.show(msg+data.name);
33     }
34
35     renderView() {
36         if (!this.state.dataArray || this.state.dataArray.length === 0)return;
37         var len = this.state.dataArray.length;
38         var views = [];
39         for (var i = 0, l = len - 2; i < l; i += 2) {
40             views.push(
41                 <View key={i}>
42                     <View style={styles.item}>
43                         {this.renderCheckBox(this.state.dataArray[i])}
44                         {this.renderCheckBox(this.state.dataArray[i + 1])}
45                     </View>
46                     <View style={styles.line}/>
47                 </View>
48             )
49         }
50         views.push(
51             <View key={len - 1}>
52                 <View style={styles.item}>
53                     {len % 2 === 0 ? this.renderCheckBox(this.state.dataArray[len - 2]) : null}
54                     {this.renderCheckBox(this.state.dataArray[len - 1])}
55                 </View>
56             </View>
57         )
58         return views;
59
60     }
61
62     renderCheckBox(data) {
63         var leftText = data.name;
64         return (
65             <CheckBox
66                 style={{flex: 1, padding: 10}}
67                 onClick={()=>this.onClick(data)}
68                 isChecked={data.checked}
69                 leftText={leftText}
70             />);
71     }
72
73     render() {
74         return (
75             <View style={styles.container}>
76                 <ScrollView>
77                     {this.renderView()}
78                 </ScrollView>
79                 <Toast ref={e=>{this.toast=e}}/>
80             </View>
81         )
82     }
83
84 }
85
86 const styles = StyleSheet.create({
87     container: {
88         flex: 1,
89         backgroundColor: '#f3f2f2',
90         marginTop:30
91     },
92     item: {
93         flexDirection: 'row',
94     },
95     line: {
96         flex: 1,
97         height: 0.3,
98         backgroundColor: 'darkgray',
99     },
100 })



react native 键盘遮挡按钮点击事件

在做项目的时候,我遇到一个很奇怪的问题,我先描述一下问题,在InputText输入内完成以后,点击按钮进行下一步的操作的时候,第一次点击的时候,按钮没有响应,第二次点击的时候才会响应。这样对用户体验有点不好。所以测试的果断提了一个bug。刚刚拿到这个问题,我一时也找不到方法,因为我检查了很几遍代码,敢拿人头打包票代码写的没有问题,那到底是什么问题呢?在我测了好几遍以后,发现了一点问题,第一次点击,键盘就会隐藏起来,然后再点击,就有用效果了。我就想,是不是键盘把按钮的点击事件给遮挡了呢?于是我就试着先把键盘给隐藏起来,然后再点击按钮,果然是这样。但是我们该怎样隐藏键盘呢?很简单。

1 import dismissKeyboard from 'dismissKeyboard';


然后再想隐藏键盘的地方加这一句,就可以隐藏了。

1  dismissKeyboard();


 http://www.cnblogs.com/huangjialin/p/6211601.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: