"Focus" prop 在数组中的文本字段之间未正确更改

"Focus" prop is not changing properly between text fields in a array

我需要在按下“Enter”按钮时在文本字段数组中向下移动光标。当我按“Enter”时,状态会正确改变,但光标不会移动。

这是我的代码

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

export default class BasicTextFields extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      cursor_index: 0,
      arr: ["sampledata", "sampledata", "sampledata"]
    };
    this.one = this.one.bind(this);
  }

  componentDidMount() {
   
  }

  one(e, index) {
    if (e.key === "Enter") {
      this.setState({
        cursor_index: index + 1
      });
    }
  }

  render() {
    return (
      <div>
        {this.state.arr.map((item, index) => {
          return (
            <TextField
              autoFocus={index == this.state.cursor_index}
              onKeyDown={(e) => {
                this.one(e, index);
              }}
              id="filled-basic"
              label="Filled"
              variant="filled"
            />
          );
        })}
      </div>
    );
  }
}

您可以将 refs array 与您的数据数组并行,并使用该信息专注于 next text input

在最后一次输入时按 enter 将再次返回到第一个输入。您可以根据需要更改这些边缘条件。

试试下面

import TextField from "@mui/material/TextField";
import React, { createRef } from "react";

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      cursor_index: 0,
      arr: ["sampledata", "sampledata", "sampledata"],
      refs: [createRef(), createRef(), createRef()]
    };
    this.one = this.one.bind(this);
  }

  componentDidMount() {}

  one(e, index) {
    if (e.key === "Enter") {
      const { arr, refs } = this.state;
      console.log();
      refs[(index + 1) % arr.length].current.focus();
    }
  }

  render() {
    return (
      <div>
        {this.state.arr.map((item, index) => {
          return (
            <TextField
              onKeyDown={(e) => {
                this.one(e, index);
              }}
              inputRef={this.state.refs[index]}
              id="filled-basic"
              label="Filled"
              variant="filled"
            />
          );
        })}
      </div>
    );
  }
}

代码沙箱 => https://codesandbox.io/s/small-waterfall-uh7p4?file=/src/App.js