反应打字稿如何将useRef用作道具

时间:2020-01-01 16:13:36

标签: reactjs typescript

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

将其作为道具传递

我尝试过

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

3 个答案:

答案 0 :(得分:1)

您需要在将引用传递到的组件上使用class Newspapers(models.Model): esp_articles = ArrayField(models.CharField(max_length=8000, blank=True)) eng_articles = ArrayField(models.CharField(max_length=8000, blank=True)) @property def articles_zipped(self): return zip(self.esp_articles, self.eng_articles) ,例如:

{% for article_spanish, article_english in news.articles_zipped %}
  <p>{{ article_spanish }}</p>
  <p>{{ article_english }}</p>
{% endfor %}

裁判员与普通道具的待遇不同。它们不包含在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} /> ); }); 。将ref暴露在组件内部之后,应将其分配给return语句中的组件之一(通常是顶级组件,在这种情况下为props)。


更新:

如果看到错误forwardRef,则应将要创建的引用类型更改为适当的引用类型:

input

,然后在输入组件中将第一行更改为:

React.HTMLElement is not assignable to type React.HTMLInputElement

答案 1 :(得分:1)

更改为:

const Input: React.FC<InputProps> = React.forwardRef((inputProps, ref) => {  
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"
      ref={ref}      
      {...inputProps}
    />
)
})
export default Input;

此处输出:https://codesandbox.io/s/typescript-useref-example-p3hh4

答案 2 :(得分:-1)

尝试以下方法之一:

  1. 使用HTMLInputElement代替HTMLElement
  2. <Input type="text" id="todo" ref={todoRef as any}/>
  3. 将HTMLElement类型包装为ReactElement泛型类型