简体   繁体   中英

How to setState with Picker in React-native?

A feature in my project in province searching but now I'm using typing the name of province and now I want to use Picker in React-native to setState from value that user selected.How can I setState from value that user selected from Picker?

My searching function and constructor.

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

My Searching box and picker.

<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" />

from the code you provided in your question i think you are new to react-native. your code is wrong( you just copied & pasted code). this part selectedValue={this.state.language} in your Picker is wrong because there is no language in your state .

imagine you have a Picker which has list of cities. and you have a variable in state named selectedCity .

so your picker would be like this :

<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>

this will make a Picker listing 2 cities( city1 - city2) and whenever user selects one of them this.setState() will be called and selectedCity in state will be initialized.

if you want to call setState in another method, just instead of

onValueChange={(itemValue, itemIndex) =>
      this.setState({ selectedCity: itemValue })
      }

use

onValueChange={(itemValue, itemIndex) =>
     //call method here!
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM