Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

reactjs - React prop type validation compiles the code without validation unlike React.PropType, is it a normal behaviour?

I am using react 17.0.1

Here when I am using the package prop-types the validation does not work, however it works well with React.PropTypes

function Tweet({ tweet }) {
  return (
    <div className="tweet">
        <LikeButton count={tweet.likes} />
    </div>
  )
}


let testTweet = {
  message: "Some message for my first tweet",
  author: {
    handle: "@myname"
  },
  likes: "3s",
}

ReactDOM.render(
  <React.StrictMode>
    <Tweet tweet={testTweet} />
  </React.StrictMode>,
  document.getElementById('root')
);

This fails:

npm i prop-types

import PropTypes from 'prop-types'
function LikeButton({count}){
  return (
    <span className="likebutton">
      <i className="fa fa-heart like-button"></i>
      {count > 0 && <span className="like-count" > {count} </span>}
    </span>
  )
} 
LikeButton.propTypes  = {
  count : PropTypes.number
}

This works:

   function LikeButton({count}){
      return (
        <span className="likebutton">
          <i className="fa fa-heart like-button"></i>
          {count > 0 && <span className="like-count" > {count} </span>}
        </span>
      )
    } 
    LikeButton.propTypes  = {
      count : React.PropTypes.number
    }

Can we make it work like React.PropTypes ?

Edit: PropTypes are great debugging tool but a failed validation won't stop code from running.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...