【问题标题】:how to check and uncheck checkbox in nested array in React native?如何在 React native 的嵌套数组中选中和取消选中复选框?
【发布时间】:2019-06-03 12:28:55
【问题描述】:

我在嵌套数组中使用了一个复选框。它的 onclick checkbox 布尔值改为 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勾选和不勾选功能如下..

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 的内部数组值选中和取消选中复选框。

它的值在单击复选框时发生变化,但复选框未选中和未选中。有什么解决办法吗?

【问题讨论】:

    标签: reactjs react-native react-native-android react-native-ios


    【解决方案1】:

    多选复选框可以这样做

    _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>
                            )}
                        />
    

    【讨论】:

      【解决方案2】:

      我正在使用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>
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 2019-09-10
        • 2015-08-02
        相关资源
        最近更新 更多