【问题标题】:How to create dynamic checkbox on JSON response in react native?如何在本机反应中创建 JSON 响应的动态复选框?
【发布时间】:2018-07-11 15:22:20
【问题描述】:

我是 React Native 中的一只新蜜蜂。如果我问重复的问题,请原谅我。我问的是相对问题,因为之前关于这个主题的问题对我没有帮助。 我想基于 JSON 响应创建动态复选框,我已经将数据收集在一个数组中,下面是代码。

sellablePartsCategory = [];

sellablePartsCategory 包含数据

sellablePartsCategory = ["Brake", "Suspension", "Engine", "Tyre"]

renderParts(){
    for(let i=0; i<sellablePartsCategory.length; i++){
      return(
        <CheckBoxComponent 
            title={sellablePartsCategory[i]}
            checked= {true} /> );
    }
}

 render(){
 <View>
    <Text> {sellablePartsCategory} </Text>
      {this.renderParts()}
 </View> }

我知道 return 语句破坏了 for 循环并使其只运行一次。它给了我数组的零索引值,然后循环中断。我不知道如何解决问题。 CheckBoxComponent.js 是

import React, { Component } from 'react';                         
import {TextInput, StyleSheet, View, Text} from 'react-native';   
import { CheckBox, ListItem, List } from 'react-native-elements';  
const CheckBoxComponent = ({title, checked}) => {
return (
    <CheckBox
        title={title}
        checkedColor='#0D4A8E'
        checked={checked}
        />
);};

export { CheckBoxComponent };

【问题讨论】:

    标签: reactjs react-native checkbox


    【解决方案1】:

    在您的renderParts() 方法中,您可以返回列表中的所有复选框,只使用一次返回。试试下面的代码:

    renderParts(){
        let checkBoxComponentList = [];
        for(let i=0; i<sellablePartsCategory.length; i++){
            checkBoxComponentList.push(<CheckBoxComponent 
                title={sellablePartsCategory[i]}
                checked= {true} />);
        }
        return checkBoxComponentList;
    }
    

    【讨论】:

    • 不要忘记 key 支持 CheckBoxComponent。你也可以使用sellablePartsCategory.map(callbackFunction)来优化这段代码)
    • 很高兴帮助 :) 也,合并您的编辑以回答 @fazeelreact :)
    • @KartalErkoc 如何处理每个要选中的复选框的 onPress 事件?
    • @fazeelreact ,这需要另一个问答线程,但只是为了给您一个想法,您可以将您的 checked 值保留为 state 在您的 state 中并在它们之间切换按下时的真假。这也需要您将 onPress 属性函数添加到您的 CheckBox 元素中,就像 checkedColorchecked 属性一样。您可以将其作为一个单独的问题提出。因为,我无法更改上面的答案,因为它解决了您最初问题的正确答案。
    • 嗨@fazeelreact,您可以将答案标记为已接受吗?这对我也有帮助:)
    猜你喜欢
    • 2016-08-24
    • 2014-12-28
    • 1970-01-01
    • 2020-06-03
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多