javascript - 在 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.
};
解决方案
根据 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
}
}
推荐阅读
- php - 在 Ubuntu 20.04 上更新 PHP 7.4 不会更新到最新版本
- python - 如何将点击从一个应用程序“镜像”到另一个应用程序?
- jquery-validate - 如何验证组中的单独字段?jQuery 验证
- css - Font Awesome 字体大小不变
- python - python,排序不起作用(随机结果)
- mysql - 从 CSV 中截断,但不从插入中截断
- c++ - 没有/proc/self/exe的Linux上C/C++运行时可执行文件的大小?
- swift - 单击按钮时如何使计数器工作?
- javascript - 将此散景图转换为 JavaScript?
- python - 如何获取子进程访问的文件列表?