Typescript和React:如何获得类型化参考?(Typescript and React: How to have typed refs?)

编程入门 行业动态 更新时间:2024-10-24 12:31:07
Typescript和React:如何获得类型化参考?(Typescript and React: How to have typed refs?)

我正在使用Typescript进行反应。 例如,如果我有一个参考

<SomeComponent ref="example-ref"></SomeComponent>

我可以通过this.refs['example-ref']以通常的方式访问它,并从那里开始工作。 如果我想输入它,我必须明确地施放它:

var typedRef: SomeComponent = this.refs['example-ref'] as SomeComponent;

但是,我怎么可以键入引用,以便我不必施放它们? 谢谢

I'm using Typescript with react. If I have a reference, for example

<SomeComponent ref="example-ref"></SomeComponent>

I can access it the usual way with this.refs['example-ref'] and work from there. If I want it typed, I have to explicitly cast it:

var typedRef: SomeComponent = this.refs['example-ref'] as SomeComponent;

But how can I have typed references so that I don't have to cast them? Thanks

最满意答案

使用替代的ref语法对我们来说很好,即在类中声明一个私有变量

private comp: SomeComponent;

然后在多伦多证券交易所

<SomeComponent ref={(c) => { this.comp = c } }/></SomeComponent>

只需在代码的其余部分访问键入的this.comp

Using an alternative refsyntax works well for us i.e. declare a private var in the class

private comp: SomeComponent;

and then in the TSX

<SomeComponent ref={(c) => { this.comp = c } }/></SomeComponent>

Just access the typed this.comp in the rest of the code

更多推荐

本文发布于:2023-07-31 20:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1347235.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   类型   React   Typescript   typed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!