我正在阅读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.
};
根据 MDN 的说法,Static 不适合 React,它是 JavaScript 的一部分:
static 关键字定义类的静态方法。 静态方法 不会在类的实例上调用。相反,他们被要求 类本身。这些通常是实用程序函数,例如函数 以创建或克隆对象。
以下是声明 propType 的两种方法,它们的工作方式相同:
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 扩展(如 Flow 或 TypeScript(对整个应用程序进行类型检查。但即使你不使用这些,React 也有一些内置的类型检查功能。要对组件的 props 运行类型检查,您可以分配特殊的 propType 属性
https://reactjs.org/docs/typechecking-with-proptypes.html
在组件中编写 propType 的另一个好处是,我们可以查看我们的 prop 及其类型。这样我们下次在应用程序中的其他地方使用相同的组件时就可以传递正确的道具。