如何更新数组-ReactNative [英] How to update the array - ReactNative

查看:291
本文介绍了如何更新数组-ReactNative的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现的是这样的 Array

infos = [{type: 'phone', val: '2222222'}
           {type: 'email', val: 'abc@abc.com'}]

这里是

constructor(props) {
super(props);
this.state = {
  rows: [], //this is used for the add component 
  contactDetails: [{type: '', val: ''}], // where i will add the values 
};
}

所以我有两个 TextInput

<View>
  <TextInput label='Type'/>
  <TextInput label='Details'/>
</View>

视图可以在单击按钮,也可以将其删除。这是我添加和删除按钮的代码:

This View can be dynamically added when a button is clicked and can also be deleted. Here is my code for the add and delete button:

addRow(){
 this.state.rows.push(index++)
 this.setState({ rows: this.state.rows })
}

deleteRow(key){
 this.state.rows.splice(key, 1)
 this.setState({ rows: this.state.rows })
}

<TouchableOpacity onPress={ this.addRow.bind(this) } >
   <Text style={{textAlign: 'center',}}>Add</Text>
</TouchableOpacity>

 ...

 <TouchableOpacity  onPress={ () => this.deleteRow(i) } >
   <Image source={require('./../img/delete.png')} style={{width:32, height: 32 }} />
 </TouchableOpacity>

如何正确获取其值并将其添加到我的 Array
谢谢。

How can I get the value of it correctly and add it to my Array? Thank you.

更新

在我的 TextInput 我尝试做过

<TextInput 
                    onChangeText={(text)=>{
                      let cd = this.state.contactDetails;
                      cd[i].val = text ;
                      this.setState({cd});

                    }}
                    value={this.state.contactDetails[i]}
                    label='Details' 
                    />

但我总是遇到错误 undefined不是对象(评估'cd [i] .val = text')

推荐答案

您不能通过以下方式操纵状态声明 this.state.rows.push(index ++),但是必须使用 concat()并返回新变量的值。例如(我实际上不知道 index 在您的情况下代表什么,但让我们尝试一下:

You can't manipulate state by declaring this.state.rows.push(index++), but you must do it with concat() and return the value to new variable. For instance (I actually don't know what index represents in your case, but let's give it a try:

addRow() {
 const rows = this.state.rows.concat(index++)
 this.setState({rows})
}

这是一个有效的示例,我假设您正在尝试实现: https://snack.expo.io/HySVtag6g

Here's a working example what I assume you're trying to achieve: https://snack.expo.io/HySVtag6g

这篇关于如何更新数组-ReactNative的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆