简体   繁体   English

你如何为 React 中必需道具的可选子属性默认默认道具?

[英]How do you default default props for an optional child property of a required prop in React?

I have a required object, but not all of it's children are required.我有一个必需的对象,但并非所有的孩子都是必需的。

For example, this is what I'm trying to do:例如,这就是我想要做的:

import PropTypes from 'prop-types';

const propTypes = {
  bike: PropTypes.shape({
    id: PropTypes.number.isRequired,
    color: PropTypes.string
  }).isRequired
}
const defaultProps = {
  bike: {
    color: 'red'
  }
}

In this example, I'm trying to say that the bike object is required with an id, but the color is not required and will be red by default.在这个例子中,我试图说需要带有 id 的自行车对象,但颜色不是必需的,默认情况下为红色。

With my ESLint rules (AirBnb's default set for the most part), I get the following error:使用我的 ESLint 规则(大部分情况下 AirBnb 的默认设置),我收到以下错误:

defaultProp "bike" defined for isRequired propType.为 isRequired propType 定义的 defaultProp "bike"。 (react/default-props-match-prop-types) (反应/默认道具匹配道具类型)

Any ideas on how to do this properly?关于如何正确执行此操作的任何想法?

This makes no sense to do anyway.无论如何,这样做毫无意义。 Default props does a shallow merge which means that when you supply the bike prop it will overwrite the default prop you set.默认道具会进行浅层合并,这意味着当您提供自行车道具时,它将覆盖您设置的默认道具。

Also, are you actually setting the default props and prop types on the component?另外,您是否真的在组件上设置了默认道具和道具类型?

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

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