Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

使用typescript的react项目中,如何声明antd的formRef的类型?

代码如下:

class App extends Component<Tprops, Tstate>{

   formRef: React.RefObject<unknown> 
   
   ......
   this.formRef = React.createRef();
   
   dosth = () => {
     // 报错 类型“RefObject<unknown>”上不存在属性“validateFields”。
     this.formRef.validateFields(...);
   }
   
   render(){
     return <Form ref={formRef}>
      ...
     </Form>
   }
}

我应该如何声明formRef这个属性的类型呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

参考 antd 中关于 form 部分的源代码

const Form = React.forwardRef<FormInstance, FormProps>(InternalForm) as <Values = any>(
  props: React.PropsWithChildren<FormProps<Values>> & { ref?: React.Ref<FormInstance<Values>> },
) => React.ReactElement;

这么写就ok了

const ref = React.createRef<FormInstance>();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...