首页 > 解决方案 > 如何在反应式原生平面列表的文本输入中更改焦点?

问题描述

我有一个调用 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>
    );
  };

标签: reactjsreact-native

解决方案


找到了解决方案!

我需要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();
  }

推荐阅读