首页 > 解决方案 > 如何在使用参考的反应js中将焦点设置为下一个输入

问题描述

我在地图中使用多个输入,当我在 React Hooks 中单击输入时,我想将焦点设置为下一个输入。在裁判的帮助下

我正在使用材质 ui 文本字段来获取输入

我尝试在没有 ref 的反应类组件中工作,但在钩子中它不能工作类组件代码:

constructor(props) {
this.state = {}
}

inputRefs = [];

 _handleKeyPress = e => {
        const {currentTarget} = e;
            let inputindex = this.inputRefs.indexOf(currentTarget)
            if (inputindex < this.inputRefs.length - 1) {
                this.inputRefs[inputindex + 1].focus()
            }
            else {
                this.inputRefs[0].focus()
            }
      };

内部渲染在地图功能中添加了这个

this.state.data.map((data) => return (
<TextField 
     inputProps = {{onKeyPress:(e) => this.function1(e, data)}}
     onChange={this.changevaluefunction} 
     inputRef={ref => this.inputRefs.push(ref)} 
     onFocus={this.handleFocus}  ref={`input${id}`} /> ))

标签: javascriptnode.jsreactjsreact-hooks

解决方案


您可以转换this.inputRefs为 React ref,以便它通过渲染持续存在,除此之外,您几乎可以删除对任何this对象的所有引用。

示例组件:

const LENGTH = 10;
const clamp = (min, max, val) => Math.max(min, Math.min(val, max));

export default function App() {
  const [data] = useState([...Array(LENGTH).keys()]);

  const inputRefs = useRef([]); // <-- ref to hold input refs

  const handleKeyPress = index => () => {                   // <-- enclose in scope
    const nextIndex = clamp(0, data.length - 1, index + 1); // <-- get next index
    inputRefs.current[nextIndex].focus();                   // <-- get ref and focus
  };

  return (
    <div className="App">
      {data.map((data, index) => (
        <div key={index}>
          <TextField
            inputProps={{ onKeyPress: handleKeyPress(index) }}   // <-- pass index
            inputRef={(ref) => (inputRefs.current[index] = ref)} // <-- save input ref
          />
        </div>
      ))}
    </div>
  );
}

编辑 how-to-set-focus-to-next-input-on-enter-key-press-in-react-js-with-refs


推荐阅读