gpt4 book ai didi

javascript - React-native 选择器默认值

转载 作者:行者123 更新时间:2023-11-29 22:54:32 28 4
gpt4 key购买 nike

我有以下代码

 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。请帮忙

最佳答案

如果它为 null 或为空,则调用选择器 Item 中的函数来设置值,如下代码所示:

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>
);
}

我想也许你也可以通过 ref 来解决这个问题。

关于javascript - React-native 选择器默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56843747/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com