reactjs - 如何在反应式原生平面列表的文本输入中更改焦点?
问题描述
我有一个调用 renderItem 方法的 FlatList,此方法返回一个包含 TextInput 的组件。我希望设置我的 textinputs 的 onSubmitEditing 方法以将焦点设置在下一个输入上。
平面列表:
<FlatList
data={this.state.itens}
keyExtractor={(i) => `${i.IdBalancoItem}`}
renderItem={this.renderItem}
/>
渲染项:
renderItem = (ItemBalanco) => {
const { item, index } = ItemBalanco;
return (
<View
style={{
flexDirection: 'row',
borderColor: '#aaa',
borderRadius: 5,
borderWidth: 1,
padding: 5,
marginBottom: 1,
}}>
<View>
<Input
returnKeyType={
this.state.itens.length - 1 === index ? 'done' : 'next'
}
keyboardType="number-pad"
value={item.Quantidade}
onChangeText={(e) => this.alteraQuantidadeItem(index, e)}
/>
</View>
</View>
);
};
解决方案
找到了解决方案!
我需要forwardRef
在我的 Input 组件中添加钩子,如下所示:
import React, { forwardRef } from 'react';
import { TextInput } from 'react-native-paper';
const Input = (props, ref) => {// NOW RECEIVE THE REF HERE
const {
onChangeText,
onSubmitEditing,
value,
placeholder,
secureTextEntry,
label,
showSoftInputOnFocus = true,
returnKeyType,
} = props;
return (
<TextInput
{...props}
dense={true}
label={label}
mode="outlined"
ref={ref}// SET THE REF HERE
secureTextEntry={secureTextEntry}
placeholder={placeholder}
value={`${value ?? ''}`}
onChangeText={(val) => {
onChangeText(val);
}}
returnKeyType={returnKeyType}
showSoftInputOnFocus={showSoftInputOnFocus}
onSubmitEditing={onSubmitEditing}
autoCapitalize="none"
autoCorrect={false}
theme={{
colors: {
placeholder: '#111',
text: '#111',
primary: '#034885',
underlineColor: 'transparent',
background: '#f2f2f2',
},
}}
/>
);
};
const forwarded = forwardRef(Input);//USE THE HOOK HERE
export default forwarded;
并且需要在 renderItem 方法的输入上添加 ref,如下所示:
<Input
returnKeyType={
this.state.itens.length - 1 === index ? 'done' : 'next'
}
ref={(r) => (this.referencias[index] = r)} //<---- THIS LINE, REFERENCIAS IS AN ARRAY OF REFS
onSubmitEditing={(e) => this._mudafoco(index)}
keyboardType="number-pad"
value={item.Quantidade}
onChangeText={(e) => this.alteraQuantidadeItem(index, e)}
方法_mudafoco(葡萄牙语改变焦点)是这样的:
_mudafoco(index) {
//checks if it's not the last item of the array to change focus
if (index !== this.state.itens.length - 1) {
let i = index + 1;
this.referencias[i].focus();
return;
}
//else it's the last item of array and I can call another method
this.handleProximo();
}
推荐阅读
- go - 无法执行 ffprobe 命令
- amazon-s3 - 从 s3 存储桶复制到 redshift 我在 stl_load_errosrs 的 raw_line 中收到系统消息
- c# - 将json复杂对象映射到普通对象
- python - 如何从Python中的字符串中间获取某些短语
- onelogin - 带有自定义参数的 SAML 设置断言
- python - 如何替换数据框中的 Year 并将该值乘以 Pandas 中的 12
- authlib - clients = self.AVAILABLE_CLIENTS[name] KeyError: 'requests' flask authlib client
- node.js - fastify-mongodb : "mongo" 在访问时未定义
- python - 如何使用 pyplot 创建曲面图?
- kotlin - 如何将 Kotlin 代码中的 null 传递给 Java 库中将 String 作为参数的方法?