Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k 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 Answer

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>();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...