如何根据状态填充和删除项目到数组?

时间:2015-12-28 14:31:35

标签: react-native react-jsx

我正在开发一个React Native Android应用程序。

我正从API接收数据(ID和名称)。现在我使用带有MKIconToggle的ListView(react-native-material-kit)来显示我的列表数据。 使用MKIconToggle,我可以为我显示的项目提供两种不同的状态(点击=颜色为黑色/未点亮=灰色)。现在我想将点击的项目列表发送回我的服务器。但我只是不知道如何将点击的项目放入数组或其他东西,只将点击的项目发送到服务器。

我使用ListView的RenderMethod如下所示:

<ListView
   dataSource={this.state.dataSource}
   renderRow={this.renderList}
   horizontal={true}
   renderHeader={this.renderHeader}
/>

RenderList:

<View
    style={{justifyContent: 'flex-start', alignItems: 'center', padding: 10, flexDirection: 'column'}}>
     <MKIconToggle
          checked={this.state.initialChecked}
          onCheckedChange={()=>this._onIconChecked(data)}
          onPress={this._onIconClicked}
          style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
        <Text state_checked={this.state.checkedState}
                      pointerEvents="none"
                      style={styles.titleChecked}
                      numberOfLines={3}>{data.name}</Text>
        <Text pointerEvents="none"
                      style={styles.title}
                      numberOfLines={3}>{data.name}</Text>
     </MKIconToggle>
</View>

现在我应该在_onIconChecked处理我点击的项目:

_onIconChecked: function (data) {

   // Put data.id into an array, if it way clicked (state is true)
   // If date.id is unclicked again, then remove from array

},

我希望我能清楚地解释我的问题,否则只是让我知道。我是编程和编写stackoverflow问题/问题的新手,所以如果我做错了,请给我提示。

1 个答案:

答案 0 :(得分:2)

根据您的信息,我必须做出一些假设才能回答您的问题。

现在我将假设已检查的处理程序正确返回与您的项目数组中的id相同的项目的“id”。

假设你的数组是:

[{name: 'Luke', id: 1'}, {name: 'Darth', id: 2'}]

如果我点击“Luke”,_onIconChecked会收到一个至少包含data的{​​{1}}个对象。

第二个假设是你有一个数组可以存储这些被点击的项目。我会把它放在你的组件之外,因为MK已经负责正确渲染一个已检查的项目。所以:

id: 1

最后一个假设是传递给var _checkedItems = [] var myComponent = React.create... 的{​​{1}}对象还包含有关复选框状态的信息,因此data为true或false。

所有这些项目的精确实施可能会有所不同,但这是我可以解决的问题。

现在你能做的是:

_onIconChecked

您现在要做的只是从date.checked数组中获取在已检查数组中包含其ID的项目:

_onIconChecked: function (data) {
  var id = data.id;
  var checked = data.checked;

  var currentIndex = _checkedItems.indexOf(id)

  if(checked) {
    if(currentIndex == -1) { _checkedItems.push(id) }
    // the 'else' would mean the item is already in the array, so no need to add
  } else {
    if(currentIndex > -1) {
      // This means that the item is in the array, so lets remove it:
      _checkedItems.splice(currentIndex, 1) // This removes the id from the array.
    }
  }
}

我不确定你的设置,所以我做了很多假设,可能过度设计了一些东西,但它可能会让你朝着正确的方向前进。

相关问题