首页 > 解决方案 > 在 reactjs 中使用静态 propTypes 有什么意义,它解决了任何问题还是只是一种模式

问题描述

我正在阅读 Web 应用程序的代码库,并且在代码中看到了一些静态 PropTypes。我不明白它解决了什么问题或为什么需要它们?

这是相同的代码。

static propTypes = {
    fetchCricketFantasyPlayers: PropTypes.func.isRequired,//I see this in action 
     selectedAlpha: PropTypes.array,// this comes from reducer or say redux
     history: PropTypes.object.isRequired // this seems to be related to redirecting etc.
 };

标签: javascriptreactjs

解决方案


根据 MDN,静态不适合 React,它是 JavaScript 的一部分:

static 关键字定义类的静态方法。不会在类的实例上调用静态方法。相反,它们是在类本身上调用的。这些通常是实用函数,例如创建或克隆对象的函数。

这里有两种声明 propTypes 的方法,它们的工作方式相同:

class App extends React.Component {
  render() {
    return null
  }
}

App.propTypes = {
  fetchCricketFantasyPlayers: PropTypes.func.isRequired,//I see this in action 
  selectedAlpha: PropTypes.array,// this comes from reducer or say redux
  history: PropTypes.object.isRequired
}

使用静态:

class App extends React.Component {
  static propTypes {
    fetchCricketFantasyPlayers: PropTypes.func.isRequired,//I see this in action 
    selectedAlpha: PropTypes.array,// this comes from reducer or say redux
    history: PropTypes.object.isRequired
  }

  render() {
    return null
  }
}

staticthis的主要区别在于您不需要实例化类来访问值。


推荐阅读