javascript - 在reactjs中使用静态propTypes有什么意义?它能解决任何问题吗?或者它只是一种模式

标签 javascript reactjs

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

这是相同的代码。

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

最佳答案

<强> Static 不适合 React,它是 JavaScript 的一部分,根据 MDN 的说法:

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

这里有两种声明 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
  }
}

static 之间的主要区别 this 的一点是,您不需要实例化该类来访问该值。

关于javascript - 在reactjs中使用静态propTypes有什么意义?它能解决任何问题吗?或者它只是一种模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55844074/

相关文章:

javascript - 替换指令链接中的 Angular 元素 html

javascript - CoffeeScript:录制语音并输出文本

javascript - 如何根据角色动态显示菜单选项

javascript - 奇怪的 JavaScript 运算符 : expr >>> 0

javascript - RequireJS:data-main不会加载文件

javascript - 弹出搜索框和平滑滚动到顶部

html - 在 React 组件中使用 <a> 标签定位导航

javascript - 如何从 MongoDB 中提取项目并在输入新项目时更新它们?

javascript - 如何将 reactjs 与 Google DFP/AdSense 一起使用

javascript - 使用 componentWillReceiveProps 多次渲染将状态从父级传递给子级