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
更多推荐
发布评论