Reactjs React defaultProps不';无法填充缺少的对象道具
如果我有一个组件,它的proptype如下Reactjs React defaultProps不';无法填充缺少的对象道具,reactjs,react-proptypes,Reactjs,React Proptypes,如果我有一个组件,它的proptype如下 import React, { Component } from 'react' import propTypes from 'prop-types' class MyComponent extends Component { /// } MyComponent.propTypes = { hidden: propTypes.string.isRequired, items: propTypes.object, at
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']
}
如果我的组件被这样调用
我希望props.attributes
填充defaultProps
值,因为它的值未定义。这是可以(轻松)实现的吗?如果你看一下
你的代码工作得很好
看看是不是打字错误之类的
同时看看你的道具类型
为什么hidden
的默认值为false
,而道具类型为string.isRequired
您的控制台可能有错误,这可能会导致
defaultProps
出现问题。好吧,这对我来说很好!您的控制台中可能还有另一个错误
这是相同的,但是您是否可以尝试在组件中添加propTypes和defaultProps,如下所示:
class MyComponent extends Component {
static propTypes = {
....
};
static defaultProps = {
....
};
}
它起作用了,检查下面的代码段: 您可能有错误,因为您需要将项作为对象传递
items: {value: 'foo', label: 'bar'}
“严格使用”;
const e=React.createElement;
const propTypes=propTypes;
类MyComponent扩展了React.Component{
建造师(道具){
超级(道具);
this.state={liked:false};
}
render(){
console.log(this.props)
if(this.state.liked){
返回“你喜欢这个”;
}
const-props=JSON.stringify(this.props)
返回e('div',null,`我已收到这些道具:${props}`)
}
}
MyComponent.propTypes={
隐藏:propTypes.string.isRequired,
项目:propTypes.object,
属性:propTypes.array
}
MyComponent.defaultProps={
隐藏:假,
项目:{},
属性:['baz','qux']
}
const domContainer=document.querySelector(“#like_button_container”);
render(e(MyComponent,{hidden:true,items:{value:'foo',label:'bar'}),domContainer)代码>
什么不起作用?对我来说,看起来你做得对。这不是打字错误?在这里很好:您需要使用双大括号,如下所示:将项从items={[value:'foo',label:'bar']}更改为items={{{value:'foo',label:'bar'}}
import PropTypes from 'prop-types';