简体   繁体   中英

Attach a property to a functional component wrapped with React.forwardRef

I have a component wrapped with React.forwardRef and it so happens that it is a compound component as well.

I'm not sure how do I maintain

Form.Item  = FormItem;

while the Form component function being wrapped with forwardRef .

const Form = React.forwardRef((props, ref) => { return <form></form>});

Typescript gives me an error (rigthly) saying

Property 'Item' does not exist on type 'ForwardRefExoticComponent>'.ts(2339)

Just to make it more clear of the solution, as it's on an external site (Credits to original author here , and thank you @Antoan Elenkov)

export interface Props = {
   ...yourPropsHere;
};

export interface CompoundedComponent extends React.ForwardRefExoticComponent<Props & React.RefAttributes<HTMLInputElement>> {
   yourStaticFunctionOrSomethingLikeThat: () => void;
}

const Component = React.forwardRef<HTMLInputElement, Props>((props, ref) => (
    <input ref={ref} {...props} />
)) as CompoundedComponent;

Component.yourStaticFunctionOrSomethingLikeThat = () => {};

This solution from the same GH thread seems nicer to me:

const Form = React.forwardRef(function Form(...) {
  ...
})

const FormItem = React.forwardRef(...)

const FormNamespace = Object.assign(Form, {Item: FormItem})

export {FormNamespace as Form}

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