Javascript 在组件外部反应类型
我以前喜欢函数式Javascript,最近我开始使用面向对象的Javascript和React库。这个问题更多的是理解代码 为什么下面的代码不起作用Javascript 在组件外部反应类型,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我以前喜欢函数式Javascript,最近我开始使用面向对象的Javascript和React库。这个问题更多的是理解代码 为什么下面的代码不起作用 class MyComponent extends React.Component{ propTypes : { name: React.PropTypes.string.isReequired, location: React.PropTypes.string } render(){
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')
);
类MyComponent扩展了React.Component{
道具类型:{
名称:React.PropTypes.string.isrequired,
位置:React.PropTypes.string
}
render(){
返回(
你好,这里是{This.props.name},我住在这里
{this.props.location}
);
}
}
ReactDOM.render(
,
document.getElementById('root'))
);
鉴于此代码有效
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')
);
类MyComponent扩展了React.Component{
render(){
返回(
你好,这里是{This.props.name},我住在{This.props.location}
);
}
}
MyComponent.propTypes={
名称:React.PropTypes.string.isrequired,
位置:React.PropTypes.string
}
ReactDOM.render(
,
document.getElementById('root'))
);
有人能帮我理解吗?谢谢。在ES6类中,静态属性如下所示
class X extends Y {
static staticThing = {
...
}
}
注意=
用ES5方式“分配”静态属性看起来像是第二种方式
通常,对于功能组件,您将使用第二种方式,而对于ES6样式的类组件,您也可以使用第一种方式(尽管使用了=
)
另外,请确保您的
React.PropTypes
正确-isRequired
应该是isRequired
在ES6类中,静态属性如下所示
class X extends Y {
static staticThing = {
...
}
}
注意=
用ES5方式“分配”静态属性看起来像是第二种方式
通常,对于功能组件,您将使用第二种方式,而对于ES6样式的类组件,您也可以使用第一种方式(尽管使用了=
)
另外,请确保您的
做出反应。PropTypes
正确-是必需的
应该是是必需的
您需要使用静态
字(定义静态属性),因为,PropTypes
需要在类
本身上声明,而不是在类
的实例上声明,并使用=
检查一下
像这样:
static propTypes = {
name: React.PropTypes.string.isRequired,
location: React.PropTypes.string
}
您需要使用
static
word(定义静态属性),因为需要在类本身而不是类的实例上声明propTypes
,并使用=
检查一下
像这样:
static propTypes = {
name: React.PropTypes.string.isRequired,
location: React.PropTypes.string
}
谢谢这是有道理的:)谢谢。这是有道理的:)谢谢。现在我明白了,谢谢。现在我明白了。