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

React两个TextField按Enter切换时onFocus属性异常、光标无法跳转问题

问题原因

autoFocus 属性仅在组件首次挂载时生效,后续修改对应 state 值不会触发重新聚焦,这就是你状态更新正常但光标没有跳转的原因。

解决方案

通过 React ref 直接获取输入框实例,按下回车时手动调用实例的 focus() 方法完成光标切换,修改后代码如下:

import React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';

export default class BasicTextFields extends React.Component {
  constructor(props) {
    super(props);
    this.one = this.one.bind(this);
    this.two = this.two.bind(this);
    // 创建两个ref存储输入框实例
    this.textField1Ref = React.createRef();
    this.textField2Ref = React.createRef();
  }

  one(e) {
    if (e.key === 'Enter') {
      e.preventDefault(); // 阻止回车默认提交行为
      // 直接让第二个输入框聚焦
      this.textField2Ref.current.focus();
    }
  }

  two(e) {
    if (e.key === 'Enter') {
      e.preventDefault();
      // 切回第一个输入框聚焦
      this.textField1Ref.current.focus();
    }
  }

  render() {
    return (
      <Box>
        <TextField
          onKeyDown={this.one}
          ref={this.textField1Ref}
          autoFocus // 首次加载默认聚焦第一个输入框
          id='filled-basic'
          label='Filled'
          variant='filled'
        />
        <TextField
          onKeyDown={this.two}
          ref={this.textField2Ref}
          id='standard-basic'
          label='Standard'
          variant='standard'
        />
      </Box>
    );
  }
}

如果你原有逻辑还需要用到one、two两个状态,可以保留相关state代码,在setState的回调函数中执行focus操作即可,效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:45:00