React-native Picker默认值

时间:2019-07-01 23:54:08

标签: javascript reactjs react-native

我有以下代码

 import React, { Component } from 'react'; 
import { Text, View,StyleSheet, Picker } from 'react-native';

 export default class App extends Component {   constructor(props) {
     super(props)

     this.state = {
       language: '',
       firstLanguage: 'java',
      secondLanguage: 'js',
    }   }
      render() {
     return (
       <View style={styles.container}>
         <Text style={styles.title}>Unstyled: {this.state.language}</Text>
         <Picker
           style={styles.picker} itemStyle={styles.pickerItem}
           selectedValue={this.state.language}
           onValueChange={(itemValue) => this.setState({language: itemValue})}

           <Picker.Item label="Java" value="java" />
           <Picker.Item label="JavaScript" value="js" />
           <Picker.Item label="Python" value="python" />
           <Picker.Item label="Haxe" value="haxe" />
         </Picker>


       </View>
     );   } }

在加载组件时,组件状态内用于语言的值为空字符串,但在选择器中选择了Java。我也希望将状态值设置为java。请帮助

1 个答案:

答案 0 :(得分:1)

在选择器项中调用一个函数以设置值是否为null或空,如以下代码所示:

export default class App extends Component {
constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.state = {
        language: '',
    };
}            

setFirstValue (value){
    if(this.state.language =='' ||this.state.language == null){
        this.setState({ language: value })
    } 
}
render() {
    return (
        <View>
            <Text>Unstyled: {this.state.language}</Text>
            <Picker
                selectedValue={this.state.language}
                onValueChange={(itemValue) => this.setState({ language: itemValue })}

            >
                <Picker.Item label="Java" value="java" STF = {this.setFirstValue("java")}  />
                <Picker.Item label="JavaScript" value="js" />
                <Picker.Item label="Python" value="python" />
                <Picker.Item label="Haxe" value="haxe" />
            </Picker>
        </View>
    );
}

}

我认为也许您也可以通过参考来解决此问题。