如何使用 useRef 和 React hooks 将焦点设置在 ReactJS 中的自定义输入上?

Fai*_*her 4 javascript reactjs react-hooks

我正在使用自定义输入元素,并希望在初始渲染后将焦点设置在它上面。这是我的自定义输入元素:(虽然很简单)

import React from 'react';
import './Input.scss';

const input = (props) => (
    <input 
        type={props.inputtype} 
        className="input" 
        placeholder={props.hint}
        style={{width: props.width}} {...props}/>
);

export default input;
Run Code Online (Sandbox Code Playgroud)

这就是我在功能组件中使用它的方式:

const SignupPopup = (props) => {

const inputEmailRef = useRef(null);
//...
useEffect(() => {
    inputEmailRef.current.focus();
}, []);

return ( 
   <Input
      inputtype="email"
      hint="Email"
      width="100%"
      id="inputemail"
      ref={inputEmailRef}
      value={email}
      required
      onBlur={emailBlurHandler}
      onChange={inputChangeHandler}
      />);
}
Run Code Online (Sandbox Code Playgroud)

错误:

类型错误:无法读取 null 的属性“焦点”

在此输入图像描述

我见过的所有示例和代码仅适用于本机<input ref={myRef} />元素,但有什么方法可以在自定义输入元素或包装输入元素中执行此操作?

小智 5

您应该在自定义组件中将React.forwardRefa 传递ref给本机:input

import React from 'react';
import './Input.scss';

const input = React.forwardRef((props, ref) => (
    <input 
        type={props.inputtype} 
        className="input" 
        placeholder={props.hint}
        style={{width: props.width}}
        ref={ref}
        {...props}
    />
));

export default input;
Run Code Online (Sandbox Code Playgroud)

更多详细信息:- https://en.reactjs.org/docs/forwarding-refs.html