简体   繁体   English

将属性附加到用 React.forwardRef 包装的功能组件

[英]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.我有一个用React.forwardRef包裹的组件,碰巧它也是一个复合组件。

I'm not sure how do I maintain我不知道我该如何维护

Form.Item  = FormItem;

while the Form component function being wrapped with forwardRef .而 Form 组件 function 用forwardRef包裹。

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

Typescript gives me an error (rigthly) saying Typescript 给我一个错误(正确地)说

Property 'Item' does not exist on type 'ForwardRefExoticComponent>'.ts(2339)类型“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)只是为了更清楚地说明解决方案,因为它在外部网站上( 此处感谢原作者,谢谢@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:来自同一个 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