首页 > 解决方案 > 无论如何要在 React 中的页面加载上进行输入自动对焦

问题描述

我有一个 SPA,当页面加载时,我的所有组件都已经呈现在屏幕上。我将特定输入设置为自动对焦,屏幕会自动拍摄到输入所在的组件,而不是停留在页面顶部。有什么方法可以阻止此功能但保持输入自动或永久集中?

标签: htmlcssreactjsinput

解决方案


我用scrollTo,希望对你有帮助。

焦点在最后一个输入

class ScrollToTop extends React.Component {
  focus = () => {
    window.scrollTo(0, 0)
  }
  render() {
    return ( <
      div >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text' / >
      <
      input type = 'text'
      onFocus = {
        this.focus
      }
      autoFocus / >
      <
      /div>
    );
  }
}



ReactDOM.render( < ScrollToTop / > ,
  document.getElementById("root")
);
div {
  display: flex;
  flex-direction: column;
}

div input {
  outline: none !important;
  line-height: 32px;
  margin-bottom: 5px;
  border-radius: 5px;
  border: solid 1px #999;
  width: 50%;
}

div input:focus {
  outline: none !important;
  border: 1px solid #00b1ff;
  box-shadow: 0 0 10px #719ECE;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


推荐阅读