简体   繁体   中英

Using forwardRef with React.FC component

I am trying to use forwardRef with React.FC component in Typescript but Im getting the following TS error:

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'.

Here is my code:

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);

I tried assinging extra props for refs like this: React.FC = ({ value, onClick, onChange }: InputProps, ref: HTMLInputElement)

But it doesnt seem to be solving the issue, any ideas how to fix this TS error?

Don't use React.FC if you don't need it.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM