在React Native Multi Select中设置Selected项目

时间:2019-10-09 10:08:58

标签: react-native

我要选择我已经选择并保存在后端的选定项目,如果我得到响应,则设置已经选择的那些我在react native multi select中设置的项目 这是我的代码,用于响应本机多选

//Example Multiple select / Dropdown / Picker in React Native
import React, { Component } from "react";
//Import React
import { View, Text, Picker, StyleSheet, SafeAreaView } from "react-native";
//Import basic react native components
import MultiSelect from "react-native-multiple-select";
//Import MultiSelect library

//Dummy Data for the MutiSelect
this.items = [
  { id: "1", name: "America" },
  { id: "2", name: "Argentina" },
  { id: "3", name: "Armenia" },
  { id: "4", name: "Australia" },
  { id: "5", name: "Austria" },
  { id: "6", name: "Azerbaijan" },
  { id: "7", name: "Argentina" },
  { id: "8", name: "Belarus" },
  { id: "9", name: "Belgium" },
  { id: "10", name: "Brazil" }
];

export default class App extends Component {
  state = {
    //We will store selected item in this
    selectedItems: [
      { id: "1", name: "America" },
      { id: "2", name: "Argentina" },
      { id: "3", name: "Armenia" },
      { id: "4", name: "Australia" }
    ]
  };

  onSelectedItemsChange = selectedItems => {
    this.setState({ selectedItems });
    //Set Selected Items
  };

  render() {
    const { selectedItems } = this.state;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={{ flex: 1, padding: 30 }}>
          <MultiSelect
            hideTags
            items={items}
            uniqueKey="id"
            ref={component => {
              this.multiSelect = component;
            }}
            onSelectedItemsChange={this.onSelectedItemsChange}
            selectedItems={selectedItems}
            selectText="Pick Items"
            searchInputPlaceholderText="Search Items..."
            onChangeInput={text => console.log(text)}
            tagRemoveIconColor="#CCC"
            tagBorderColor="#CCC"
            tagTextColor="#CCC"
            selectedItemTextColor="#CCC"
            selectedItemIconColor="#CCC"
            itemTextColor="#000"
            displayKey="name"
            searchInputStyle={{ color: "#CCC" }}
            submitButtonColor="#48d22b"
            submitButtonText="Submit"
          />

          <View>
            {this.multiSelect &&
              this.multiSelect.getSelectedItemsExt(selectedItems)}
          </View>
        </View>
      </SafeAreaView>
    );
  }
}

2 个答案:

答案 0 :(得分:0)

知道了。

this.state={
  selectedData: "158" // list of id here(without space, that is your response of api)
};

 <MultiSelect          
     .....
     .....
     selectedItems={selectedData}
 />
 <View>
     {this.multiselect ? this.multiSelect.getSelectedItemsExt(selectedData): null}
 </View>

enter image description here

答案 1 :(得分:0)

我遇到了同样的问题,我想出了如何通过使用部分可接受的答案来预设选择。 我了解到selectedItems是在MultipleSelect道具中设置为uniqueKey的列表。

例如,如果将uniqueKey用作每个列表成员的编号ID,并且希望选择第二个成员集,则您将拥有selectedItems = {[“ 2”]}

我希望这是有道理的。