将动态引用保存到react native中类组件中的数组只保存最后一个索引



我有一个带有动态创建视图的类组件,我想访问这些视图引用,所以我决定将所有引用保存在对象数组中,以便以后访问它们。但每当我尝试访问ref时,它总是引用最后一个索引,这意味着map索引总是只等于最后一个值。

这里有一个例子来演示的行为


import React, {Component} from 'react';
import {View, Text, TextInput, Button} from 'react-native';
class myComponent extends Component {
constructor(props) {
super(props);
this.state = {};
}
data = [1, 2, 3];
inputsRefs = new Array(3).fill({
input1: null,
input2: null,
index: null,
});
async componentDidMount() {}
render() {
return (
<View>
{this.data.map((x, i) => {
this.inputsRefs[i].index = i;
return (
<View key={i+''}>
<TextInput ref={ref => (this.inputsRefs[i].input1 = ref)} />
<TextInput ref={ref => (this.inputsRefs[i].input2 = ref)} />
</View>
);
})}
<Button
title="print indexes"
onPress={() => {
console.log(this.inputsRefs.map(x => x.index));
//the result is [2,2,2] while it should be [0,1,2]
}}
/>
</View>
);
}
}
export default myComponent;

编辑添加密钥不会影响的结果

尝试在map循环内设置key道具。这里是渲染方法:

...
render() {
return (
<View>
{this.data.map((x, i) => {
this.inputsRefs[i].index = i;
return (
<View key={`key-${i}`}>
<TextInput ref={ref => (this.inputsRefs[i].input1 = ref)} />
<TextInput ref={ref => (this.inputsRefs[i].input2 = ref)} />
</View>
);
})}
<Button
title="print indexes"
onPress={() => {
console.log(this.inputsRefs.map(x => x.index));
//the result is [2,2,2] while it should be [0,1,2]
}}
/>
</View>
);
}
...

最新更新