反应:为什么静态 propTypes
react: why static propTypes
我正在寻找 redux todomvc codes。 static propTypes
中的 static
关键字是什么?
propTypes
不是组件实例所独有的。它们也不会因组件而改变。因此,将它们作为 class.
的静态成员是有意义的
static
不是上一代 Javascript ("ES5") 的一部分,这就是为什么您不会在旧文档中找到它的原因。然而,除 Internet Explorer (http://caniuse.com/#search=es6), and if you use a transpiler like Babel you can use it in any browser. Most React users are already using Babel to transpile their JSX, so React sites (like Redux TodoMVC) take it for granted. You can read more about static
here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static.
外,所有主流浏览器现在都支持 "ES6" class 语法的其余部分
在 static propTypes
的情况下,propTypes 需要在 class 本身上声明,而不是在 class 的实例上声明。也就是说,如果你使用无状态组件:
function Foo() {
this.PropTypes = somePropTypes; // bad
return <div></div>;
}
Foo.PropTypes = somePropTypes; // good
当使用 ES6 classes 时,Foo.PropTypes = somePropTypes
等价于:
class Foo extends React.Component {
static PropTypes = somePropTypes;
}
作为旁注,在 class 中定义属性的能力在任何浏览器中都不存在(目前):你需要一个转译器,例如带有 transform-class-properties
插件的 Babel .
我正在寻找 redux todomvc codes。 static propTypes
中的 static
关键字是什么?
propTypes
不是组件实例所独有的。它们也不会因组件而改变。因此,将它们作为 class.
static
不是上一代 Javascript ("ES5") 的一部分,这就是为什么您不会在旧文档中找到它的原因。然而,除 Internet Explorer (http://caniuse.com/#search=es6), and if you use a transpiler like Babel you can use it in any browser. Most React users are already using Babel to transpile their JSX, so React sites (like Redux TodoMVC) take it for granted. You can read more about static
here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static.
在 static propTypes
的情况下,propTypes 需要在 class 本身上声明,而不是在 class 的实例上声明。也就是说,如果你使用无状态组件:
function Foo() {
this.PropTypes = somePropTypes; // bad
return <div></div>;
}
Foo.PropTypes = somePropTypes; // good
当使用 ES6 classes 时,Foo.PropTypes = somePropTypes
等价于:
class Foo extends React.Component {
static PropTypes = somePropTypes;
}
作为旁注,在 class 中定义属性的能力在任何浏览器中都不存在(目前):你需要一个转译器,例如带有 transform-class-properties
插件的 Babel .