React:嵌套的 defaultProps 深度合并 [英] React: Nested defaultProps deep merge

查看:46
本文介绍了React:嵌套的 defaultProps 深度合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下定义的 track 道具:

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
    })
  }

如果未定义,我希望 track.cover 获得默认值:

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

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

我有机会在视图级别做到这一点吗?getDefaultProps 是否进行深度合并?还是我需要在模型级别处理这个问题?

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?

谢谢

推荐答案

getDefaultProps 不会将传递的属性值与指定的返回值合并.如果该属性不存在,React 将使用 getDefaultProps 返回的对象来初始化组件实例.

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.

例如下面的代码产生:

Test Cover and

代码:

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);

另外,请注意 getDefaultProps 中返回的对象在组件的所有实例之间共享 (参考).

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

这篇关于React:嵌套的 defaultProps 深度合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆