Arrays 如何更新数组-ReactNative
我试图实现的是这样一个Arrays 如何更新数组-ReactNative,arrays,react-native,react-native-android,Arrays,React Native,React Native Android,我试图实现的是这样一个数组 infos = [{type: 'phone', val: '2222222'} {type: 'email', val: 'abc@abc.com'}] info: { type: '', val: '', } 这是状态 constructor(props) { super(props); this.state = { rows: [], //this is used for the add component
数组
infos = [{type: 'phone', val: '2222222'}
{type: 'email', val: 'abc@abc.com'}]
info: {
type: '',
val: '',
}
这是状态
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>
如何正确获取它的值并将其添加到我的数组中
?
多谢各位
更新 在我的
TextInput
中,我尝试了这样做
<TextInput
onChangeText={(text)=>{
let cd = this.state.contactDetails;
cd[i].val = text ;
this.setState({cd});
}}
value={this.state.contactDetails[i]}
label='Details'
/>
{
设cd=this.state.contactDetails;
cd[i].val=text;
this.setState({cd});
}}
值={this.state.contactDetails[i]}
标签class='Details'
/>
但是我总是有一个错误
未定义不是对象(计算'cd[I].val=text')
您不能通过声明this.state.rows.push(index++)
来操纵状态,但必须使用concat()
并将值返回到新变量。例如(实际上,我不知道在您的案例中索引代表什么,但让我们试一试:
addRow() {
const rows = this.state.rows.concat(index++)
this.setState({rows})
}
下面是一个我假设您正在尝试实现的工作示例:在我的状态下,我添加了一个如下数组
infos = [{type: 'phone', val: '2222222'}
{type: 'email', val: 'abc@abc.com'}]
info: {
type: '',
val: '',
}
然后我把它添加到我的addRow
addRow(){
//add new array in contactDetails
var arrayvar = this.state.contactDetails.slice()
arrayvar.push(this.state.info)
this.setState({ contactDetails: arrayvar })
//add new component row
this.state.rows.push(index++);
this.setState({ rows: this.state.rows});
}
每次单击添加按钮时,带有空值的
数组
命名信息将添加到contactDetails
,然后我更新添加数组的值。我只对显示类型和值的组件使用行数组。我有另一个数组,它是contactDetails,我想在其中保存t文本输入中输入的类型和值