![](/img/trans.png)
[英]How to use React.forwardRef() in in functional component react js
[英]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.