【问题标题】:How to focus next input (if any) on next press如何在下一次按下时聚焦下一个输入(如果有)
【发布时间】:2023-03-11 10:00:03
【问题描述】:

我实际上知道如何做到这一点,但我需要一种不同的方法。
所以我有如下文本输入:

<TextInput returnKeyType='next' 
           ref={ref => this.someName = ref}
           onSubmitEditing={(event) => { this.nextFieldName.focus() }}/>

诀窍是我不想为下一个字段使用特定名称,而是简单地关注下一个(如果有的话)。
这可能吗?

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    你的问题有点宽泛。如果您提供更多详细信息,我可能会有所帮助,但现在让我举个例子。

    假设您有一组数据,您正在映射并创建一个表单。

    const data = [
      {
        type: 'text',
        value: 'name'
      },
      {
        type: 'text',
        value: 'surname'
      },
      {
        type: 'number',
        value: 'age'
      }
    ];
    

    现在让我们遍历数据

    data.map((field, index) => {
      return (
        <TextInput
          type={field.type}
          value={this.state[field.value]}
          ref={(ref) => this.refs[index] = ref}
          onSubmitEditing={() => this.onSubmitEditing(index)}
        />
      );
    });
    

    现在因为我们知道我们在哪个字段上以及是否存在另一个字段,我们可以关注或提交表单。

    onSubmitEditing = (index) => {
      if (data.length <= (index + 1)) {
        this.refs[index + 1].focus();
      } else {
        // no input to move 
        // submit form
      }
    }
    

    【讨论】:

    • 我都是这样做的。我刚刚使用了类似的字符串: ref={ref => this.refs[item.UniqueName] = ref} 并且在 onSubmitEditing() 处理程序内部 this.refs[] 是空的。解决方案是添加 this.refs = [];在构造函数中。
    • 你在构造函数中初始化this.refs = {}了吗?您也可以尝试使用其他名称。 this.refs 可能不起作用,因为 React 也在使用。尝试使用类似this.fields={} 然后(ref) =&gt; this.fields[item.UniqueName]=ref
    • @bennygenel 我已经试过了,我的this.refs 只是返回一个空对象&& this.fields 只是在我尝试记录它时导致我的应用程序崩溃,这在以后的版本中是否有所改变注册护士?
    • 你在设置 refs 吗?
    • 是的,我是。在我的构造函数this.refs = {}
    【解决方案2】:

    假设您有 2 个 textInputs,那么如果您按 next,这就是下一个输入的焦点:

    <TextInput returnKeyType='next' 
           onSubmitEditing={(event) => { this.someName.focus() }}
    />
    
    <TextInput returnKeyType='next' 
           ref={ref => this.someName = ref}
    />
    

    【讨论】:

    • 这就是我的问题是如何在没有参考的情况下制作它。
    • @1110 没有 ref 你不能,因为如果不告诉 react-native 要关注哪个组件,它不会做任何事情。 ref 提供对组件的引用,并告诉 react-native 关注这个组件。
    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2022-07-28
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多