PropType形状-声明时引发错误

时间:2018-07-31 07:42:57

标签: reactjs react-native react-proptypes

我正在为我的组件之一创建一个形状对象。但是在编译时出错。我对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

1 个答案:

答案 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

    })
 }