簡體   English   中英

將 forwardRef 與 React.FC 組件一起使用

[英]Using forwardRef with React.FC component

我正在嘗試在 Typescript 中將 forwardRef 與 React.FC 組件一起使用,但我收到以下 TS 錯誤:

const Input: React.FC<InputProps>
Argument of type 'FC<InputProps>' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, InputProps>'.
  Types of property 'defaultProps' are incompatible.
    Type 'Partial<InputProps> | undefined' is not assignable to type 'undefined'.
      Type 'Partial<InputProps>' is not assignable to type 'undefined'.

這是我的代碼:

import React, { forwardRef } from 'react';
import style from './CustomInput.module.css';
interface InputProps {
    value: string;
    onChange: (value: string) => void;
    onClick: () => void;
}

const Input: React.FC<InputProps> = ({ value, onClick, onChange }, ref) => {
    return (
        <input
            className={style.CustomInput}
            type="text"
            value={value}
            ref={ref}
            onChange={e => onChange(e.target.value)}
            onClick={onClick}
        />
    );
};

export default forwardRef(Input);

我嘗試為這樣的引用分配額外的道具: React.FC = ({ value, onClick, onChange }: InputProps, ref: HTMLInputElement)

但它似乎並沒有解決問題,有什么想法可以解決這個 TS 錯誤嗎?

如果不需要,不要使用React.FC

function Input({value, onClick, onChange}: InputProps, ref) {
  return (
    <input
      className={style.CustomInput}
      type="text"
      value={value}
      ref={ref}
      onChange={e => onChange(e.target.value)}
      onClick={onClick}
    />
  );
});


export default forwardRef(Input);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM