我正在为我的组件之一创建一个形状对象。但是在编译时出错。我对reactjs
陌生,有人在这里帮助我吗?
这是我的声明:我的声明方式有误,请以正确的方式帮助我。
function Tweet({tweet}) {
return (
<div className="tweet">
<Avatar hash={tweet.gravatar} />
<div className="content">
<NameWithHandle author={tweet.author} /> <Time time={tweet.timestamp} />
<Message text={tweet.message} />
<div className="buttons">
<ReplyButton />
<RetweetButton count={tweet.retweets} />
<LikeButton count={tweet.likes} />
<MoreOptionsButton />
</div>
</div>
</div>
)
}
Tweet.PropTypes.shape({
message:PropTypes.string.isRequired,
gravatra:PropTypes.string.isRequired,
author:PropTypes.shape({
handle:PropTypes.string.isRequired,
name:PropTypes.string.isRequired
}),
likes:PropTypes.number.isRequired,
retweets:PropTypes.number.isRequired,
timestamp:PropTypes.string.isRequired
})
var testTweet = {
message: "Something about cats.",
gravatar: "xyz",
author: {
handle: "catperson",
name: "IAMA Cat Person"
},
likes: 2,
retweets: 0,
timestamp: "2016-07-30 21:24:37"
}
获取错误为:
index.js:106 Uncaught TypeError: Cannot read property 'shape' of undefined
答案 0 :(得分:2)
PropTypes
定义shape
验证者。
Tweet
组件对象的属性shape
应该使用propTypes
属性定义
应该的。
Tweet.propTypes = {
someObj : PropTypes.shape({
message:PropTypes.string.isRequired,
gravatra:PropTypes.string.isRequired,
author:PropTypes.shape({
handle:PropTypes.string.isRequired,
name:PropTypes.string.isRequired
}),
likes:PropTypes.number.isRequired,
retweets:PropTypes.number.isRequired,
timestamp:PropTypes.string.isRequired
})
}