Javascript 如何在React native中使用选择器设置状态?

Javascript 如何在React native中使用选择器设置状态?,javascript,react-native,picker,setstate,Javascript,React Native,Picker,Setstate,我的项目中的一项功能是在省搜索,但现在我正在使用键入省的名称,现在我想在React native to setState(从用户选择的值到设置状态)中使用Picker。如何从用户从Picker中选择的值设置状态 我的搜索函数和构造函数 constructor(props) { super(props); this.state = { currentCity: "Phuket", searchText: "" }; this.handleSubmit =

我的项目中的一项功能是在省搜索,但现在我正在使用键入省的名称,现在我想在React native to setState(从用户选择的值到设置状态)中使用Picker。如何从用户从Picker中选择的值设置状态

我的搜索函数和构造函数

  constructor(props) {
    super(props);
    this.state = {
     currentCity: "Phuket",
     searchText: ""
 };
 this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
 event.preventDefault();
 const { searchText } = this.state;
 this.refs.modal3.close();
 this.setState({ currentCity: searchText });
}
我的搜索框和选择器

<TextInput
        placeholder="City name"
        ref={el => (this.element = el)}
        style={styles.textInput}
        value={this.state.searchText}
        onChangeText={searchText => this.setState({ searchText })}
      />
      <View>
        <Button style={styles.btn} onPress={this.handleSubmit}>
          <Text style={styles.submitText}>Submit</Text>
        </Button>
      </View>
      {//Dropdown Picker
      }
      <Picker
        selectedValue={this.state.language}
        style={{ height: 50, width: 200 }}
        onValueChange={(itemValue, itemIndex) =>
          this.setState({ language: itemValue })
        }
      >
        <Picker.Item label="Amnat Charoen" value="1906689" />
        <Picker.Item label="Ang Thong" value="1621034" />
        <Picker.Item label="Bangkok" value="1609350" />
(this.element=el)}
style={style.textInput}
值={this.state.searchText}
onChangeText={searchText=>this.setState({searchText})}
/>
提交
{//下拉选择器
}
this.setState({language:itemValue})
}
>

根据您在问题中提供的代码,我认为您是一个新手。您的代码错误(您刚刚复制并粘贴了代码)。您的
选择器
中的这部分
selectedValue={this.state.language}
是错误的,因为您的
状态
中没有
语言

假设您有一个
选择器
,其中包含城市列表。在状态中有一个变量名为
selectedCity

因此,您的选择器将如下所示:

<Picker
  selectedValue={this.state.selectedCity}
  onValueChange={(itemValue, itemIndex) =>
  this.setState({ selectedCity: itemValue })
  }
 >
   <Picker.Item label="city1" value="1" />
   <Picker.Item label="city2" value="2" />
</Picker>
使用


您似乎已经在做
onValueChange={(itemValue,itemIndex)=>this.setState({language:itemValue})}
另外它是
reactjs
react native
不要同时使用这两个标签。我只是从react native的文档中复制了这段代码,我不知道如何正确使用它。你能建议我吗。如果我想在用户选择时关闭选择器的窗体,我如何在选择器中使用handleSubmit?
onValueChange={(itemValue, itemIndex) =>
      this.setState({ selectedCity: itemValue })
      }
onValueChange={(itemValue, itemIndex) =>
     //call method here!
      }