reactjs - React defaultProps 不会填充缺失的对象 Prop

标签 reactjs react-proptypes

如果我有一个组件,其 propTypes 如下

import React, { Component } from 'react'
import propTypes from 'prop-types'

class MyComponent extends Component {
    ///
}

MyComponent.propTypes = {
    hidden: propTypes.string.isRequired,
    items: propTypes.object,
    attributes: propTypes.array
}

MyComponent.defaultProps = {
    hidden: false,
    items: {},
    attributes: ['baz', 'qux']
}

如果我的组件是这样调用的
<MyComponent hidden={true} items={[value: 'foo', label: 'bar']} />
我希望 props.attributes填充了 defaultProps值,因为它的值没有定义。这是可以(轻松)实现的吗?

最佳答案

如果你看 this example on codesandbox .

您的代码工作正常!

看看它是不是打字错误或类似的东西。

还要看看你的 Prop 类型。

为什么默认为hiddenfalse , 但 Prop 类型是 string.isRequired ?

您的控制台上可能有错误,这可能会导致 defaultProps 出现问题。 .

关于reactjs - React defaultProps 不会填充缺失的对象 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776285/

相关文章:

javascript - react .js : Wrapping one component into another

javascript - 无法读取未定义的属性 'string' | React.PropTypes

reactjs - React PropTypes : At least one of these props must be provided

javascript - 使用相同的表单更新添加的数据 | react 堆

javascript - ReactJS setState 为空白对象不起作用

reactjs - 如何解决 "React.PropTypes.shape is not a function"?

react-native - 错误 : Component [ComponentName] declared `PropTypes` instead of `propTypes` . 您是否拼错了属性分配?

javascript - 检查 PropTypes 是否是有效的 JSON

css - 在 reactJS 中设置背景

javascript - 映射未定义但仍打印到控制台