每当我从picker
中选择一个项目时,我都会尝试调用函数
,并使用alert
显示所选项目。
这就是我正在做的:-
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
throttlemode:'',
}
}
GetSelectedThrottleModeItem=(throttlemode)=>{
Alert.alert(this.state.throttlemode)
}
render() {
return (
<View style={styles.MainContainerAddCamp}>
<Text style={{fontSize: 12}}> Throttle Mode</Text>
<Picker style={styles.PickerStyleClass}
selectedValue={this.state.throttlemode}
onValueChange={(throttlemodeValue, throttlemodeIndex) => this.GetSelectedThrottleModeItem(this.setState({throttlemode:throttlemodeValue}))}>
<Picker.Item label="Asap" value="asap" />
<Picker.Item label="Even" value="even" />
</Picker>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
backgroundColor:'#87ceeb',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#FF5722',
}
});
此代码显示先前选择的值。我怎样才能让它显示当前选择的值。
请指出我错过的地方。
最佳答案
首先,setState
方法不返回任何内容。其次,调用setState
方法后,你无法知道状态是否改变,这是因为setState
方法是异步的。您可以为 setState
方法的第二个参数分配回调以了解状态更改。
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
throttlemode:'',
}
}
onPickerValueChange=(value, index)=>{
this.setState(
{
"throttlemode": value
},
() => {
// here is our callback that will be fired after state change.
Alert.alert("Throttlemode", this.state.throttlemode);
}
);
}
render() {
return (
<View style={styles.MainContainerAddCamp}>
<Text style={{fontSize: 12}}> Throttle Mode</Text>
<Picker style={styles.PickerStyleClass}
selectedValue={this.state.throttlemode}
onValueChange={this.onPickerValueChange}>
<Picker.Item label="Asap" value="asap" />
<Picker.Item label="Even" value="even" />
</Picker>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
backgroundColor:'#87ceeb',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#FF5722',
}
});
关于javascript - 在选择器项目选择上调用函数 native react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667802/