reactjs – React.Component.defaultProps对象被覆盖,没有合并?
我正在尝试使用对象文字设置defaultProp,但过了一段时间后我意识到React类构造函数没有将默认道具与应用的道具合并,所以我最终得到了defaultProps文字中任何属性的未定义值尚未包含在应用道具中.有没有办法合并默认道具和应用道具,还是我需要将我的对象分解成几个道具?
class Test extends React.Component { constructor(props) { super(props); //props.test is only {one: false} //props.test.two is undefined } render() { return (<div>render</div>) } } Test.defaultProps = { test: { one: true,two: true } } ReactDOM.render(<Test test={{'one': false}}/>,document.getElementById('#test')); http://codepen.io/adjavaherian/pen/oYNPLz
React只对默认道具和实际道具进行浅层合并,即嵌套的默认道具被覆盖而不是合并.这是设计的.
有关更多背景和推理,请参阅this React issue,为什么会出现这种情况和可能的解决方法:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |