React: Nested defaultProps deep merge

后端 未结 1 1329
心在旅途
心在旅途 2021-01-17 09:57

I have a track prop with the following definition:

  propTypes: {
    track: React.PropTypes.shape({
      cover: React.PropTypes.string,
               


        
相关标签:
1条回答
  • 2021-01-17 10:18

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

    0 讨论(0)
提交回复
热议问题