【问题标题】:React and TypeScript, how to properly define direct properties of my component class?React 和 TypeScript,如何正确定义我的组件类的直接属性?
【发布时间】:2019-01-24 15:23:52
【问题描述】:

我刚刚开始使用 TypeScript,但遇到了一个错误。我经常在构造函数中初始化 refs 但 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?或者,这是一种反模式,我应该以不同的方式定义 refs 吗?

【问题讨论】:

  • 我不是 React 专家,但您似乎只需将 target 声明为该类的属性。就像private target: Whatever-Type-React.createRef-Returns在构造函数之上
  • 哦,哇,这似乎很明显,但我就是无法理解它,谢谢
  • 如果您想要添加引用的组件的类型信息(以及可能附带的函数,例如:ScrollView 组件的 scrollTo),我建议您查看我的回答。

标签: reactjs typescript react-native


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我就是这样做的,这样你就可以得到你的 ref 的所有必要的类型信息。例如:一个滚动视图

    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});
      }
    }
    

    【讨论】:

      【解决方案3】:

      你在构造函数中声明的目标是错误的,这样做

      class MyComponent extends React.PureComponent<types.MyComponentProps>
        constructor(props: MyComponentProps){
          super(props);
      
        }
      this.target = React.createRef();
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2019-08-27
        • 2020-03-19
        • 1970-01-01
        • 2014-11-05
        • 2017-02-19
        • 2017-08-31
        • 2021-06-03
        • 2019-01-30
        相关资源
        最近更新 更多