我只是玩 typescript 和
我在自定义元素中使用 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;
请问正确的做法是什么?
更新
我解决了:
https://codesandbox.io/s/typescript-useref-example-e0hc4
最佳答案
您需要使用 React.forwardRef
在您将 ref 传递给的组件上,如下所示:
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}
/>
);
});
Refs 的处理方式与普 channel 具不同。它们不包含在
props
中目的。要在自定义组件中公开 ref,您必须使用 forwardRef
.一旦 ref 在您的组件中公开,您应该将其分配给 return 语句中的组件之一(通常是顶级组件,在这种情况下 input
)。更新:
如果您看到错误
React.HTMLElement is not assignable to type React.HTMLInputElement
您应该将正在创建的 ref 类型更改为适当的类型:const todoRef = useRef<HTMLInputElement | null>(null)
并在输入组件中将第一行更改为:
const Input = React.forwardRef<HTMLInputElement, InputProps>(({ ...inputProps }, ref) => {
关于reactjs - react typescript 如何使用 useRef 作为 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554049/