【问题标题】:anyway to make an input autofocus on page load in React无论如何要在 React 中的页面加载上进行输入自动对焦
【发布时间】:2021-10-16 08:08:11
【问题描述】:

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

【问题讨论】:

    标签: html css reactjs input


    【解决方案1】:

    我用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>

    【讨论】:

      猜你喜欢
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多