React用props在类组件内部调用静态函数

时间:2019-12-23 05:19:57

标签: reactjs typescript class redux react-redux

反应+ Redux +类组件+打字稿+ ES6

当我需要从不同组件中取出通用逻辑时,
我创建一个通用类来放置服务。
并想像下面一样使用

MyServiceClass.commonMethodUsingProps()

我知道在这种情况下我们需要使用static
一切进展顺利,直到某些逻辑与redux数据相关,以下消息才出现。

  

类型'typeof Component'.ts(2339)上不存在属性'props'

这里有什么问题吗? 我已经检查了质量检查passing-props-to-a-static-react-componentscall-a-static-function-into-the-class-react-es6,请提醒我是否遗漏了一些东西。

interface Props {
  xxx: Store['xxx'],
}
interface State {
}

class Component extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
    };
  }

  static commonMethodUsingProps() {
    this.props.xxx // <= ooops! Property 'props' does not exist on type 'typeof Component'.ts(2339)  
  }
}

export const MyServiceClass = connect(
  (store: Store) => ({
    xxx: store.xxx,
  }),
  (dispatch: any) => ({
  })
)(Component);

还有(如果有)使用类组件编写带有redux道具的重用逻辑/服务的其他模板吗?
请注意,如果没有React组件,请参考此is-it-possible-to-connect-non-component-class-to-redux-store

我已经做到了,但是有点丑陋

export class MyServiceClass() {
  static A(props: any, ...) {
    MyServiceClass.B(props, ...)
  }
  static B(props: any, ...) {
    MyServiceClass.C(props, ...)
  }
  static C(props: any, ...) {
    MyServiceClass.commonMethodUsingProps(props, ...)
  }
  static commonMethodUsingProps(props: any, ...) {
    props.xxx
  }
}
MyServiceClass.A(this.props, ...)

2 个答案:

答案 0 :(得分:1)

在静态方法中,this不是您的实例对象,而是类对象。如果您运行代码MyServiceClass.commonMethodUsingProps(),您会期望this.props是什么?

因此,您要么必须手动传递道具,要么根本不使用static方法。

我会争辩说,如果您希望函数访问this.props,那么您不是想要静态方法,而是想要一个普通方法,其中this是您的实例。 / p>

答案 1 :(得分:0)

要么创建一个正常的函数,该函数就会更改道具并将“ this”绑定到您的函数。或将props作为参数传递,然后对其进行变异。