简体   繁体   English

可以在 proptype 形状中使用默认值吗?

[英]Can a default value be used in a proptype shape?

Is it possible to define a type for an object's with a required key value pair and a default key value pair?是否可以为具有所需键值对和默认键值对的对象定义类型?

Example:例子:

const myComponent = (props) => {
  const {
    myObject: {
      someRequiredString,
      someNotRequiredString,
    }
  }
}

myComponent.propTypes = {
  myObject: PropTypes.shape({
    someRequiredString.string.isRequired,
  }).isRequired,
}

myComponent.defaultProps = {
  myObject: {
    someNotRequiredString: '',
  }
}

So if i understand you correct, you need non-required object bit if this object exist it's must have 2 required field, and maybe one non-required所以如果我理解你是正确的,如果这个对象存在,你需要非必需的对象位,它必须有 2 个必填字段,也许一个非必需字段

So here we are:所以我们在这里:

componentForUser.propTypes = {
    myObject: PropTypes.shape({
        name:PropTypes.string.isRequired,
        secondName:PropTypes.string.isRequired,
        age:PropTypes.string,
    }),
}

componentForUser.defaultProps = {
    myObject: {
        name: 'defaultName',
        secondName: 'defaultSecondName',
        age:21
    }
}

In this case if User object is not required, instead of this you will get User with properties:在这种情况下,如果不需要 User 对象,您将获得具有属性的 User:

myObject: { name: 'defaultName', secondName: 'defaultSecondName', age:21 }

But if from props you will get object User without name, you catch Warning about required name and secondName.但是,如果从 props 中您将获得没有名称的对象 User,则会收到有关所需名称和第二个名称的警告。

也许自从提出这个问题以来这已经改变了,但是你不能为这样的嵌套值提供 defaultProps 。

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

相关问题 React native Undefined不是对象(评估'_react3.default.PropType.shape') - React native Undefined is not an object(evaluating'_react3.default.PropType.shape') React native Undefined不是对象(评估'_react3.default.PropType.shape')吗? - React native Undefined is not an object(evaluating'_react3.default.PropType.shape')? 如何使用已由另一个 propType 接口定义的动态键和值来验证 propType 形状? - How can I validate a propType shape with dynamic keys and values already defined by another propType interface? 参数可以用作默认值吗 - Can parameters be used as default value 根据组件重用需要或不需要道具的通用 PropType 形状 - Reusing a common PropType shape with props required or not required depending on the component 如何设置/伪造组件的proptype - How can I set/fake the proptype of a component 您是否可以为javascript函数参数设置一个默认值,该参数仅在根本不传递该参数时使用? - Can you set a default value for a javascript function argument that is only used if the argument is not passed at all? 从另一个模块导入PropType值会导致未定义 - Importing PropType value from another module results in undefined 如何声明对应于可为空数字的 PropType? - How can I declare a PropType corresponding to a nullable number? useHistory 可以作为 useRef 的值吗? - Can useHistory can be used as a value of useRef?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM