You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组渲染的TextField的Focus属性未正常切换,按Enter无法移动光标

问题原因

你当前的写法问题出在autoFocus属性仅在组件首次挂载渲染时生效,后续状态更新修改autoFocus的值不会重新触发聚焦逻辑,所以游标状态更新了但输入框焦点没有切换。

解决方案

通过手动存储输入框DOM引用,状态更新后主动调用聚焦方法实现跳转:

import TextField from "@mui/material/TextField";
import React from "react";

export default class BasicTextFields extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cursor_index: 0,
      arr: ["sampledata", "sampledata", "sampledata"]
    };
    // 存储所有输入框的原生DOM引用
    this.inputRefs = [];
    this.one = this.one.bind(this);
  }

  one(e, index) {
    if (e.key === "Enter") {
      // 阻止回车默认行为(避免换行、意外表单提交等问题)
      e.preventDefault();
      const nextIndex = index + 1;
      // 边界判断,避免索引超出数组长度报错
      if (nextIndex < this.state.arr.length) {
        this.setState({
          cursor_index: nextIndex
        }, () => {
          // setState是异步操作,放在回调中保证状态更新完成后再触发聚焦
          this.inputRefs[nextIndex]?.focus();
        });
      }
    }
  }

  render() {
    return (
      <div>
        {this.state.arr.map((item, index) => {
          return (
            <TextField
              autoFocus={index === this.state.cursor_index}
              onKeyDown={(e) => this.one(e, index)}
              // 通过inputRef直接绑定输入框DOM到引用数组
              inputRef={el => this.inputRefs[index] = el}
              id={`filled-basic-${index}`}
              label="Filled"
              variant="filled"
            />
          );
        })}
      </div>
    );
  }
}

修改说明

  • 新增inputRefs数组存储每个输入框的原生DOM节点,通过TextField的inputRef属性绑定,跳过组件封装层直接拿到可操作的输入框实例
  • 增加边界判断逻辑,避免游标超过数组长度时出现报错
  • 修复了所有输入框共用同一个ID的不规范问题,给每个输入框生成独立ID

内容的提问来源于stack exchange,提问作者user15684452

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:15:06