React和TypeScript,如何正确定义组件类的直接属性?

时间:2019-01-24 15:23:52

标签: reactjs typescript react-native

我刚开始使用TypeScript,但遇到了错误。我经常在构造函数中初始化ref,但TypeScript不喜欢它,请考虑以下问题:

class MyComponent extends React.PureComponent<types.MyComponentProps>
  constructor(props: MyComponentProps){
    super(props);

    // error here: Property 'target' does not exist on type 'MyComponent'
    this.target = React.createRef(); 
  }
}

我知道React.PureComponent接受props的参数和state的参数,但是如何让TypeScript知道我的组件应该直接期望属性,例如refs?或者,这是一种反模式,我应该以不同的方式定义引用吗?

3 个答案:

答案 0 :(得分:2)

您应将target初始化为类属性:

class MyComponent extends React.PureComponent<types.MyComponentProps>
  target = React.createRef(); 

  constructor(props: MyComponentProps){
    super(props);
    // May not need a constructor at all
  }
}

答案 1 :(得分:2)

这是我这样做的方式,这样您就可以获取所有必需的类型信息供您的引用使用。例如:ScrollView

interface Props {}

interface State {}

class SomeComponent extends React.PureComponent<Props, State> {

  private target: React.RefObject<ScrollView>; // or some other type of Component

  constructor(props: Props){
    super(props);

    this.target = React.createRef(); 
  }

  public render(): JSX.Element {
    return (
      <ScrollView ref={this.target}>
        ...
      </ScrollView>
    );
  }

  // now you can define a scrollToTop method for instance
  private scrollToTop = (): void => {
    // The scrollTo method is available from autocomplete since it was defined as a ScrollView ref
    this.scrollViewRef.current.scrollTo({ x: 0, y: 0, animated});
  }
}

答案 2 :(得分:0)

您在构造函数中声明了目标,这是错误的,像这样

class MyComponent extends React.PureComponent<types.MyComponentProps>
  constructor(props: MyComponentProps){
    super(props);

  }
this.target = React.createRef();
}