簡體   English   中英

將屬性附加到用 React.forwardRef 包裝的功能組件

[英]Attach a property to a functional component wrapped with React.forwardRef

我有一個用React.forwardRef包裹的組件,碰巧它也是一個復合組件。

我不知道我該如何維護

Form.Item  = FormItem;

而 Form 組件 function 用forwardRef包裹。

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

Typescript 給我一個錯誤(正確地)說

類型“ForwardRefExoticComponent>”.ts(2339) 上不存在屬性“項目”

只是為了更清楚地說明解決方案,因為它在外部網站上( 此處感謝原作者,謝謝@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 = () => {};

來自同一個 GH 線程的這個解決方案對我來說似乎更好:

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

const FormItem = React.forwardRef(...)

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

export {FormNamespace as Form}

暫無
暫無

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

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