gpt4 book ai didi

javascript - 在组件外部 react propTypes

转载 作者:行者123 更新时间:2023-11-28 13:08:42 25 4
gpt4 key购买 nike

我之前很喜欢函数式 Javascript,最近我开始使用面向对象的 Javascript 和 React 库。这个问题更多的是理解代码。

为什么下面的代码不起作用

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')
);

尽管此代码有效,

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')
);

有人可以帮我理解这一点吗?谢谢。

最佳答案

您需要使用 static 一词(定义静态属性),因为 propTypes 需要在 class 本身上声明,而不是在 class 的实例上,并使用 =

检查DOC .

像这样:

static propTypes = {
name: React.PropTypes.string.isRequired,
location: React.PropTypes.string
}

关于javascript - 在组件外部 react propTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com