[英]How can i set focus to only one TextInput in list item after TouchableOpacity pressed in this item?
I have a list of many items where each item has TextInput and TouchableOpacity wrapped by View.我有许多项目的列表,其中每个项目都有由 View 包装的 TextInput 和 TouchableOpacity。 I've trying to set focus on TextInput in the list item in which TouchableOpacity has been pressed.我试图将焦点放在已按下 TouchableOpacity 的列表项中的 TextInput 上。 It's needed for editing each item's name.编辑每个项目的名称时需要它。
Below is the code of how I tried to do this.下面是我如何尝试执行此操作的代码。 The problem of this code is that after pressing on any of the TouchableOpacity the last TextInput will always be focused due to the fact that the last iteration overwrites textInputRef
.这段代码的问题是,在按下任何 TouchableOpacity 后,最后一个 TextInput 将始终被聚焦,因为最后一次迭代覆盖了textInputRef
。
Is there a way to make textInputRef
contain a reference to the TextInput which TouchableOpacity will press?有没有办法让textInputRef
包含对 TouchableOpacity 将按下的 TextInput 的引用?
const ListComponent = ({list}) => {
const textInputValue = useRef('');
const textInputRef = useRef(null);
changeItemName = (text) => {
textInputValue.current = text;
};
return (
<ScrollView>
{list.length > 0 &&
list.map((item) => (
<View key={item._id}>
<TouchableOpacity>
<View
<Text>{`Item: `}</Text>
<TextInput ref={textInputRef} onChangeText={changeItemName}>
{item.name}
</TextInput>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
textInputValue.current = '';
}}>
<Icon name={'check'} size={25} color="#000" />
</TouchableOpacity>
<View>
<TouchableOpacity
onPress={() => {
textInputValue.current = item.name;
textInputRef.current.focus();
}}>
<Icon name={'edit'} size={25} color="#000" />
</TouchableOpacity>
</View>
</View>
))}
</ScrollView>
);
};
I think creating an array of ref will help you to resolve.我认为创建一个 ref 数组将帮助您解决问题。
Try this way试试这个方法
const ListComponent = ({list}) => {
const textInputValue = useRef('');
const textInputRef = useRef(null);
changeItemName = (text) => {
textInputValue.current = text;
};
const collectionRef = useRef(list.map(() => createRef()));
return (
<ScrollView>
{list.length > 0 &&
list.map((item, index) => (
<View key={item._id}>
<TouchableOpacity>
<View
<Text>{`Item: `}</Text>
<TextInput ref={collectionRef.current[index]} onChangeText={changeItemName}>
{item.name}
</TextInput>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
textInputValue.current = '';
}}>
<Icon name={'check'} size={25} color="#000" />
</TouchableOpacity>
<View>
<TouchableOpacity
onPress={() => {
textInputValue.current = item.name;
collectionRef[index].current.focus();
}}>
<Icon name={'edit'} size={25} color="#000" />
</TouchableOpacity>
</View>
</View>
))}
</ScrollView>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.