简体   繁体   English

在 React 应用程序中应该使用 isRequired for PropType vs defaultProps 的场景是什么

[英]What are the scenarios one should use isRequired for PropType vs defaultProps in React Application

I constantly struggle to understand, when exactly should I be using .isRequired vs .defaultProps={...} My thought is that, I think I should never ever really need to use isRequired, because it seems manually creating a bug that can break in the application because create isRequired automatically remove the need to add a corresponding default prop, that makes me feel uncomfortable just because it means I won't be able to expect a fail-safe value.我一直在努力理解,我究竟应该在什么时候使用.isRequired vs .defaultProps={...}在应用程序中,因为 create isRequired 自动删除了添加相应默认道具的需要,这让我感到不舒服,因为这意味着我将无法期望故障安全值。

It definitely sounds an opinion based question, but I look for a better opinion that makes more sense if there is one.这听起来绝对是一个基于意见的问题,但我正在寻找一个更好的意见,如果有的话,它会更有意义。

Using prop types is a good way of documenting the API for a component, so that other people know how it works without reading the code.使用 prop types 是记录组件 API 的好方法,这样其他人无需阅读代码就知道它是如何工作的。

The way it's usually thought of is the component is guaranteed to render without errors if all the required props are supplied.通常的想法是,如果提供了所有必需的 props,组件就可以保证无错误地呈现。 The props that are not required would only enhance the component with additional functionality.不需要的道具只会增强组件的附加功能。

Consider this example考虑这个例子

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      {avatarUrl && <img src={avatarUrl} />}
    </div>
  );
}

UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  avatarUrl: PropTypes.string
};

Now, if you want to render a default profile picture if it's not supplied, you could remove the conditional check inside the component and provide a default value instead.现在,如果您想要呈现未提供的默认个人资料图片,您可以删除组件内的条件检查并提供默认值。

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      <img src={avatarUrl} />
    </div>
  );
}

UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  avatarUrl: PropTypes.string
};

UserCard.defaultProps = {
  avatarUrl: "/assets/generic-picture.png"
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM