“onFocus”属性在两个文本字段之间未正确更改

2024-01-12

当我从textfield1按“Enter”时,我需要将光标从textfield1移动到textfield2,当我从textfield2按“Enter”时,我需要将光标从textfield2移动到textfield1。
当我从 textfield2 和 textField2 按“Enter”键时,状态会正确更改,但光标不会在文本字段之间移动。

这是我的代码。

export default class BasicTextFields extends React.Component {
  constructor(props) {
    super(props);
    this.one = this.one.bind(this);
    this.two = this.two.bind(this);

    this.state = {
      one: true,
      two: false,
    };
  }

  one(e) {
    console.log(e.key);
    if (e.key == 'Enter') {
      this.setState(
        {
          two: true,
          one: false,
        },
        () => {
          console.log(this.state);
        }
      );
    }
  }

  two(e) {
    if (e.key == 'Enter') {
      this.setState(
        {
          two: false,
          one: true,
        },
        () => {
          console.log(this.state);
        }
      );
    }
  }

  render() {
    return (
      <Box>
        <TextField
          onKeyDown={this.one}
          autoFocus={this.state.one}
          id='filled-basic'
          label='Filled'
          variant='filled'
        />

        <TextField
          onKeyDown={this.two}
          autoFocus={this.state.two}
          id='standard-basic'
          label='Standard'
          variant='standard'
        />
      </Box>
    );
  }
}

对于 DOM 操作,对于管理输入元素的焦点,您可以使用反应参考文献 https://reactjs.org/docs/refs-and-the-dom.html.

使用 React Refs —— 假设你的 refs 被分别调用inputOne and inputTwo— 您将能够致电this.inputTwo.current.focus()将焦点放在第二个输入上。如需了解更多信息,请查看酒店currentRef 的返回 HTML DOM 节点。

还有一件事要记住,因为你的<input>标签位于子组件中,但是您需要从两个输入的父组件控制焦点,您必须在父组件中声明引用,并转发引用,这要归功于React.forwardRef。也可以看看转发参考文献 https://reactjs.org/docs/forwarding-refs.html.

这里是demo https://stackblitz.com/edit/react-8ywruh

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“onFocus”属性在两个文本字段之间未正确更改 的相关文章

随机推荐