React typescript如何使用useRef作为prop

use*_*366 7 typescript reactjs

我只是在玩打字稿,但在自定义元素中使用 useRef 时遇到问题

将其作为 prop 传递

我尝试过

import React from "react";

export interface InputProps
  extends React.InputHTMLAttributes<HTMLInputElement> {
    ref: HTMLElement | null
  }

const Input: React.FC<InputProps> = ({ ...inputProps }) => {
  return (
    <input
      className="px-2 py-1 text-gray-700 text-2xl bg-white border-2 border-gray-200 hover:border-purple-300 focus:outline-none focus:bg-white rounded-l-lg shadow-md"
      {...inputProps}
    />
  );
};
export default Input;


import React, { useRef } from "react";

import Input from "./input";
import Button from "./button";

const Form: React.FC = () => {
  const todoRef = useRef<HTMLElement | null>(null);
  return (
    <form onSubmit={}>
      <Input type="text" id="todo" ref={todoRef}/>
      <Button type="submit">+</Button>
    </form>
  );
};

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

请问什么是正确的方法?

更新

我锻炼了: https://codesandbox.io/s/typescript-useref-example-e0hc4

JMa*_*ine 3

您需要React.forwardRef在将引用传递到的组件上使用,如下所示:

const Input = React.forwardRef<HTMLElement, InputProps>(({ ...inputProps }, ref) => {
  return (
    <input
      ref={ref}
      className="px-2 py-1 text-gray-700 text-2xl bg-white border-2 border-gray-200 hover:border-purple-300 focus:outline-none focus:bg-white rounded-l-lg shadow-md"
      {...inputProps}
    />
  );
});
Run Code Online (Sandbox Code Playgroud)

Refs 的处理方式与普通道具不同。它们不包含在props对象中。要在自定义组件中公开引用,您必须使用forwardRef. 一旦 ref 在组件内部公开,您应该将其分配给 return 语句中的组件之一(在本例中通常是顶级组件input)。


更新:

如果您看到错误,React.HTMLElement is not assignable to type React.HTMLInputElement您应该将创建的引用类型更改为适当的类型:

const todoRef = useRef<HTMLInputElement | null>(null)
Run Code Online (Sandbox Code Playgroud)

并在输入组件中将第一行更改为:

const Input = React.forwardRef<HTMLInputElement, InputProps>(({ ...inputProps }, ref) => {
Run Code Online (Sandbox Code Playgroud)