Javascript Flow认为即使在包装到if语句中后,该值也是空的
Javascript Flow认为即使在包装到if语句中后,该值也是空的,javascript,reactjs,flowtype,Javascript,Reactjs,Flowtype,this.collapsable是一个React Ref,类型为?HTMLElement。我正在尝试设置一种样式,如下所示: this.collapsible.style.height = ... 而且,尽管将上述内容包装在一个if(this.collapsable&&this.collapsable.style)中,但flow似乎仍然认为this.collapsable.style可以为空 Cannot get this.collapsible.style because property
this.collapsable
是一个React Ref,类型为?HTMLElement
。我正在尝试设置一种样式
,如下所示:
this.collapsible.style.height = ...
而且,尽管将上述内容包装在一个if(this.collapsable&&this.collapsable.style)
中,但flow似乎仍然认为this.collapsable.style
可以为空
Cannot get this.collapsible.style because property style is missing in null or undefined [1].
97│
98│ componentDidMount() {
99│ if (this.collapsible && this.collapsible.style) {
100│ this.collapsible.style.height = getInitialHeight(this.props);{
:
[1] 148│ collapsible: ?HTMLElement;
如何解决这个问题?正如@John Ruddell所指出的,给变量取别名是有效的
if (this.collapsible) {
const collapsible: HTMLElement = this.collapsible;
collapsible.style.height = getInitialHeight(this.props);
我无法找到一种不必创建新变量就可以强制转换类型的好方法。如果更显式,会发生什么?像
this.collpasible!=空值
?@四个好问题。我尝试了if(this.collapsable!=null&&this.collapsable.style!=null)
结果就是您可以尝试对变量进行别名测试吗const-elemDefinitelyExists:HTMLElement=this.collapsable
如果(this.collapsable)检查,则getInitialHeight
将使您的检查无效。我会把它移到if
块之外,然后把它放在一个变量中。然后,将if
中该变量的结果分配给您的this.collablable.style.height
@JohnRuddell,它可以工作!