как установить и снять флажок во вложенном массиве в React native? - PullRequest
0 голосов
/ 03 июня 2019

Я использовал флажок во вложенном массиве.Его флажок onclick Логическое значение изменено на true false, но мой флажок не отмечен и не отмечен.

Вот код для флажка, используемого в scrollView ....

<ScrollView
  scrollEventThrottle={16}
  style={{ backgroundColor: '#e7e7e7', }}>
  {this.state.ExampleQuestions.map((item, index) => {
    return (
      <View style={{ padding: 5 }}>
        <Card style={{
          flexDirection: 'column',
          backgroundColor: 'white',
          padding: 10
        }}>

          <View style={styles.oval}>
            <Text numberOfLines={10} style={styles.welcome}>
              ({index + 1})- {item.question_description.toString().replace(/<\/?[^>]+(>|$)/g, "")}
            </Text>
          </View>

          {item.question_type == 2 &&
            item.answers.map((itemtwo, indextwo) => {
              itemtwo.status = ""
              console.log('status', itemtwo.status)
              return (
                <View style={{
                  flex: 1,
                  flexDirection: 'row',
                  backgroundColor: 'white',
                  alignItems: 'center', margin: 5, padding: 8,
                  elevation: 1, borderRadius: 5, borderWidth: 0.7,
                  borderColor: '#C9C9C9',
                }}>
                  <View style={{ flex: 0.15, flexDirection: 'column' }}>
                    <CheckBox checked={itemtwo.status}
                      onPress={() => {
                        itemtwo.status!=itemtwo.status
                        this.CheckBox(item, itemtwo, index, indextwo)
                        console.log("render status", itemtwo.status)
                      }} />
                  </View>
                  <View style={{ flex: 1, justifyContent: 'center', flexDirection: 'column', }}>
                    <Text numberOfLines={10} style={{
                      fontSize: 15, paddingEnd: 5,
                      fontWeight: '500', textAlign: 'left',
                      fontFamily: Platform.OS === 'ios' ? Fonts.SanFranciscoDisplay_Medium : 'roboto_medium',
                      color: "black"
                    }}>{itemtwo.answer_options.toString().replace(/<\/?[^>]+(>|$)/g, "")}</Text>
                  </View>
                </View>

              )
            })

          }

Флажок отмечени непроверенная функция выглядит следующим образом ..

CheckBox(item, itemtwo, index, indextwo) {

    console.log(item, itemtwo, index, indextwo)
    console.log(itemtwo.status)


        item.answers.map((itemnew,indexnew)=>{
          if(itemnew.answer_options==itemtwo.answer_options){
            itemtwo.status = !itemtwo.status
            if(itemtwo.status==true){
            const answerValue=this.state.ExampleQuestions[index].answers[indexnew].answer_options
            this.state.ExampleQuestions[index].answers.find(v => v.answer_options == answerValue).status = true
            console.log('selected:' , itemtwo.status + itemtwo.answer_options)
            return itemtwo.status
          }
          else if (itemtwo.status==""){
            const answerValue=this.state.ExampleQuestions[index].answers[indexnew].answer_options
            this.state.ExampleQuestions[index].answers.find(v => v.answer_options == answerValue).status = ""
            console.log('unselected:' ,itemtwo.status + itemtwo.answer_options)
            return itemtwo.status
          }

        }
        })
    console.log('Final array checked', this.state.ExampleQuestions)
  }

Мой массив находится здесь:

(5) […]
​
0: {…}
​​
answers: (4) […]
​​​
0: Object { answer_options: "4", is_answer: true, status: "" }
​​​
1: Object { answer_options: "5", is_answer: "", status: true }
​​​
2: Object { answer_options: "6", is_answer: "", status: true }
​​​
3: Object { answer_options: "7", is_answer: true, status: true }
​​​
length: 4
​​​
<prototype>: Array []
​​
marks: 2
​​
q_id: 209
​​
question_description: "<p>WHAT IS THE ANSWER OF 2+2?</p>\n"
​​
question_type: 2

Ниже приводится массив данных.Я хочу установить и снять флажок, используя внутреннее значение массива с именем Status.

Его значение изменяется при щелчке, но флажок не отмечен и не отмечен.есть ли решение?

Ответы [ 2 ]

0 голосов
/ 03 июня 2019

Я использую react-native-check-box, который принимает отмеченные как boolean, а также поддерживает изображение для отмеченных и непроверенных.

У меня есть такой список

state = {
 array = [
  {
    text: "first text",
    checked: false, 
  },
  {
   text: "first text",
   checked: false, 
  }
  ]
}

Здесь я использую FlatList

<FlatList
  data={list.items}
  contentContainerStyle={{ marginRight: 15 }}
  renderItem={(obj: Object) => ListRow(obj.item, obj.index,
    () => onChange(obj.item, obj.index))}
/>

Мой ListRow выглядит следующим образом. В строке списка я обновляю listArray в состоянии. Который перезапускает метод рендеринга и список обновляется.

const ListRow = (item: Object, index: number, onSelect: Function) => (
<View style={styles.contentContainer}>
  <View key={item.id} style={styles.checkListRow} >
    <CheckBox
    style={styles.checkBoxStyle}
    onClick={onSelect} // here I am updating the checked attribute of listArray
    isChecked={item.done}
    checkedImage={<Image source={checkedBox} style={{ height: 30, width: 30 }} />}
    unCheckedImage={<Image source={greyBox} style={{ height: 30, width: 30 }} />}
  />
  <View style={styles.itemLabelContainer}>
    <Text style={styles.itemLabelStyle}>
      {/* {item.name.slice(0, 1).toUpperCase() + item.name.slice(1, item.name.length)} */}
      {item.name || 'Chicken'}
    </Text>
    <Text style={styles.quantityText}>Qty: {item.qty} {item.unit || null}</Text>
  </View>
</View>
</View>
)
0 голосов
/ 03 июня 2019

Вы можете сделать это для флажка множественного выбора

_onItemSelectDeselect(item, index) {

        let selecedItemDict = item
        if (selecedItemDict.isSelected) {
            selecedItemDict.isSelected = false
        } else {
            selecedItemDict.isSelected = true
        }
        let defectiveParts = this.state.defectivePartsList
        defectiveParts[index] = selecedItemDict

        this.setState({
            defectivePartsList: defectiveParts
        })

    }

<FlatList


 numColumns={2}
                    data={this.state.defectivePartsList}
                        extraData={this.state}
                        keyExtractor={(item) => item.type}
                        renderItem={({ item, index }) => (
                            <TouchableOpacity style={{ flex: 1, padding: 0 }} onPress={() => this._onDefectiveItemSelectDeselect(item, index)}>
                                <View style={{ borderWidth: 0, height: 40, flexDirection: 'row' }} >

                                </View>
                            </TouchableOpacity>
                        )}
                    />
...