[英]React propTypes outside Component
I was into functional Javascript previously, Recently I started with Object oriented Javascript and React Library. 以前我曾经学习过功能性Javascript,最近我开始使用面向对象的Javascript和React Library。 This question is more of understanding the code.
这个问题更多的是理解代码。
Why below code don't work 为什么下面的代码不起作用
class MyComponent extends React.Component{
propTypes : {
name: React.PropTypes.string.isReequired,
location: React.PropTypes.string
}
render(){
return(
<h1>Hello This is {this.props.name} and I live in
{this.props.location}</h1>
);
}
}
ReactDOM.render(
<MyComponent name="Node" location="DOM"/>,
document.getElementById('root')
);
Whereas this code works, 尽管此代码有效,
class MyComponent extends React.Component{
render(){
return(
<h1>Hello This is {this.props.name} and I live in {this.props.location}</h1>
);
}
}
MyComponent.propTypes = {
name: React.PropTypes.string.isReequired,
location: React.PropTypes.string
}
ReactDOM.render(
<MyComponent name="Node" location="DOM"/>,
document.getElementById('root')
);
Can someone help me understand this? 有人可以帮我理解吗? Thanks.
谢谢。
You need to use static
word (to define the static property) because, propTypes
need to be declared on the class
itself, not on the instance of the class
, and use =
. 您需要使用
static
词(以定义static属性),因为propTypes
需要在class
本身而不是在class
的实例上声明,并使用=
。
Like this: 像这样:
static propTypes = {
name: React.PropTypes.string.isRequired,
location: React.PropTypes.string
}
Inside an ES6 class, static properties look like this 在ES6类中,静态属性如下所示
class X extends Y {
static staticThing = {
...
}
}
note the =
注意
=
"assigning" a static property the ES5 way looks like the second way you have it there ES5方法“分配”静态属性的方式类似于您在其中拥有它的第二种方法
Typically, you'll use the second way for functional components whereas you might as well use the first way (albeit properly with an =
) for ES6 style class components. 通常,对于功能组件,您将使用第二种方法,而对于ES6样式类组件,则最好也使用第一种方法(尽管带有
=
)。
also, make sure you have your React.PropTypes
correct - isReequired
should be isRequired
另外,确保您的
React.PropTypes
正确isReequired
应该是isRequired
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.