reactjs - React defaultProps Not Displaying Default Value for username in Functional Component - Stack Overflow

It is the second time that I try to define a defaultProps on React, but isn't showing nothing, lik

It is the second time that I try to define a defaultProps on React, but isn't showing nothing, like is undefined

The UserGreeting component:

import PropTypes from 'prop-types'

function UserGreeting(props) {

    if (props.isLoggedIn)  {
        return (
            <h2>
                Welcome {props.username}!
            </h2>
        )
    } else {
        return (
            <h2>
                Please Log in!
            </h2>
        )
    }

}

UserGreeting.proptypes = {
    isLoggedIn: PropTypes.bool,
    username: PropTypes.string,
}

UserGreeting.defaultProps = {
    isLoggedIn: false,
    username: "Guest",
}

export default UserGreeting

And the App component:

import UserGreeting from "./UserGreeting"

function App() {
  

  return (
    <>
      <UserGreeting isLoggedIn={true} username="Bob" />
    </>
  )
}

export default App

When i run it, just show as the props is undefined when nothing is passed

It worked when I did this: Welcome {props.username ?? "Guest"}!

But i really want to understand why the defaultProps isn't working

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745170303a4614884.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信