React: Nested defaultProps deep merge

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

I have a track prop with the following definition:

  propTypes: {     track: React.PropTypes.shape({       cover: React.PropTypes.string,       title: React.PropTypes.string,       artist: React.PropTypes.string     })   } 

I would like the track.cover to get a default value if undefined:

getDefaultProps: function() {     return {       track: {           cover: 'placeholder.png'         }       }   } 

Any chance I can do that at the view level? Does getDefaultProps does a Deep Merge? Or do I need to handle this at the model level?

Thanks

回答1:

getDefaultProps does not merge passed property values with the return value specified. If the property does not exist, React will use the object returned by getDefaultProps to initialize the component instance.

The code below for example produces:

Test Cover and 

Code:

var TrackItem = React.createClass({   render: function() {     var track = this.props.track;     return (<div>{track.cover} and {track.artist}</div>);   },   getDefaultProps: function() {     return {       track: {           artist: 'def artist'         }       }   }         });  var track = {     cover: 'Test Cover'     }; React.render(<TrackItem track={ track } />, mountNode); 

Also, note that objects returned in getDefaultProps are shared across all instances of a component (reference).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!