本文純原創(chuàng),純手打,請大神多多指教。轉(zhuǎn)載請注明出處!
react-native版本:0.48; 開發(fā)環(huán)境win10+VScode; 最后更新時(shí)間:2017.09.15;
關(guān)于Picker官方給出的代碼是這樣的
<Picker
selectedValue={this.state.language}
onValueChange={(itemValue, itemIndex) => this.setState({language: itemValue})}>
<Picker.Item label="Java" value="java" />
<Picker.Item label="JavaScript" value="js" />
</Picker>
這個(gè)數(shù)據(jù)源是寫死的,并沒有給出動態(tài)數(shù)據(jù)源的例子,實(shí)際操作中大部分?jǐn)?shù)據(jù)源是動態(tài)的,下面給出我寫的動態(tài)寫法
效果圖,有些地方?jīng)]錄下來,實(shí)際情況請自行執(zhí)行代碼
這里寫圖片描述
代碼
"use strict"
import React, { Component } from 'react'
import {
AppRegistry,
View,
Text,
Picker,
StyleSheet
} from 'react-native'
// 網(wǎng)絡(luò)獲取的數(shù)據(jù),內(nèi)容必須是簡單數(shù)據(jù),不可是對象
export default class Test extends Component {
constructor(props) {
super(props)
this.state = {
pickerValue: '暫無數(shù)據(jù)',
data:[]
}
}
//本人項(xiàng)目需要,這句代碼可忽略
static navigationOptions = {
header: null
}
//模擬聯(lián)網(wǎng)
componentWillMount(){
this.setState({
data : [
'name1',
'name2',
'name3',
'name4',
'name5',
]
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>{this.state.pickerValue}</Text>
<Picker style={styles.picker}
selectedValue={this.state.pickerValue}
mode={'dropdown'} //'dialog'彈窗 'dropdown'下拉
onValueChange={(value) => {
this.setState({ pickerValue: value, })
if (value == 'name5') {
alert('處理數(shù)據(jù)')
}
}}>
<Picker.Item label={'請選擇'} value={'請選擇'} />
{this.state.data.map((name) => <Picker.Item label={name} value={name} />)}
</Picker>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
},
text: {
marginTop: 30,
backgroundColor: 'red',
width: 200,
fontSize: 20,
},
picker: {
marginTop: 30,
backgroundColor: 'cyan',//給Picker設(shè)置背景顏色后,下拉箭頭將會消失
width: 200,
},
})