开发者社区 问答 正文

#React 如何将输入元素集中在页面加载上?

#React 如何将输入元素集中在页面加载上?

展开
收起
因为相信,所以看见。 2020-05-07 19:21:33 758 分享 版权
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    您可以通过为元素创建refinput并在中使用它来实现componentDidMount():

    class App extends React.Component{
      componentDidMount() {
        this.nameInput.focus()
      }
    
      render() {
        return (
          <div>
            <input
              defaultValue={'Won\'t focus'}
            />
            <input
              ref={(input) => this.nameInput = input}
              defaultValue={'Will focus'}
            />
          </div>
        )
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('app'))
    
    2020-05-07 19:22:06
    赞同 展开评论
问答分类:
问答地址: