【问题标题】:Conver myRef to hooks version将 myR 转换为 hooks 版本
【发布时间】:2019-12-20 19:48:07
【问题描述】:

我找到了这个答案:ReactJS and autofocus

但我不知道如何转换:

constructor(props) {
    super(props);
    this.myRef = React.createRef();
}

componentDidMount(){
  this.myRef.current.focus();
}

<input type="text"  ref={this.myRef} />

响应钩子版本。

我试过这样做:

const myRef = () => {
  React.createRef().current.focus();
}

<input type="text"  ref={myRef} />

但出现错误:

TypeError: Cannot read property 'focus' of null

【问题讨论】:

    标签: javascript reactjs autofocus


    【解决方案1】:

    除了useRef,您还需要使用useEffect,它在渲染后运行。 [] 表示it only runs once

    import React, { useRef, useEffect } from 'react';
    
    function Component() {
    
      const ref = useRef(null);
    
      useEffect(() => {
        ref.current.focus();
      }, []);
    
      return <input type="text"  ref={ref} />;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 2021-12-29
      • 1970-01-01
      • 2013-03-08
      • 2019-10-03
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多