如何使用新的Typescript strictPropertyInitialization选项使用React引用?

时间:2018-04-17 09:17:45

标签: reactjs typescript

以下是我编写的用于帮助我使用Bootstrap的Popover功能的类。

import * as React from "react"
import {PureComponent, SyntheticEvent} from "react";
import {EventUtil} from "appUtil/EventUtil";

export interface PopoverProps extends React.HTMLProps<HTMLElement>{
  popoverTitle: string | Element | Function;
  popoverContent: string | Element | Function;
  container?: string;
  allowDefaultClick?: boolean;
}

export class Popover
extends PureComponent<PopoverProps, object> {

  selfRef: HTMLSpanElement;

  componentDidMount(): void{
    $(this.selfRef).popover({
      container: this.props.container || this.selfRef,
      placement: "auto",
      title: this.props.popoverTitle,
      content: this.props.popoverContent,
      trigger: "focus",
    });
  }

  stopClick = (e: SyntheticEvent<any>) =>{
    if( !this.props.allowDefaultClick ){
      EventUtil.stopClick(e);
    }
  };

  render(){
    // tabIndex is necessary when using "trigger=focus" to get 
    // "dismiss on next click" behaviour 
    return <span 
      tabIndex={0}
      ref={(ref)=>{if(ref) this.selfRef = ref}} 
      data-toggle="popover"
      onClick={this.stopClick}
    >
      {this.props.children}
    </span>;

  }
}

这很好用,但是当我启用strictPropertyInitialization时,编译器会报告:

TS2564: Property 'selfRef' has no initializer and is not definitely assigned in the constructor.

注意:我已经通过使用明确赋值运算符解决了这个问题,即

selfRef!: HTMLSpanElement;

但这似乎并不像“正确的事” - 我觉得这只是突出了我没有做正确的事情我如何使用React refs,但我不是正确的方式是

我不想声明selfRef可能未定义。

这应该如何运作?

1 个答案:

答案 0 :(得分:0)

您可以使用明确赋值运算符!,它告诉编译器字段将以其他方式初始化

selfRef! :HTMLSpanElement;