2016-06-30 11 views
14

Czy istnieje sposób w React, aby zapewnić domyślne rekwizyty do zagnieżdżonej tablicy elementów o określonym kształcie?Jak zapewnić domyślne rekwizyty dla zagnieżdżonego kształtu w React?

Biorąc pod uwagę poniższy przykład, moja pierwsza próba jest widoczna, jednak nie działa zgodnie z oczekiwaniami.

static propTypes = { 
    heading: PT.string, 
    items: PT.arrayOf(PT.shape({ 
     href: PT.string, 
     label: PT.string, 
    })).isRequired, 
}; 

static defaultProps = { 
    heading: 'this works', 
    items: [{ 
     href: '/', 
     label: ' - this does not - ', 
    }], 
}; 

W tym przykładzie byłoby oczekiwać, następujące:

// Given these props 
const passedInProps = { 
    items: [{ href: 'foo', href: 'bar' }] 
}; 

// Would resolve to: 
const props = { 
    heading: 'this works', 
    items: [ 
     { href: 'foo', label: ' - this does not - ' }, 
     { href: 'bar', label: ' - this does not - ' }, 
    ] 
}; 

Odpowiedz

14

nr domyślne podpory są tylko płytko połączone.

Jednak jednym podejściem może być komponent Dziecko dla każdej pozycji. W ten sposób każdy komponent potomny otrzymuje jeden obiekt z tablicy item, a następnie rekordy domyślne zostaną scalone zgodnie z oczekiwaniami.

Na przykład:

var Parent = React.createClass({ 

    propTypes: { 
    heading: React.PropTypes.string, 
    items: React.PropTypes.arrayOf(React.PropTypes.shape({ 
     href: React.PropTypes.string, 
     label: React.PropTypes.string, 
    })).isRequired 
    }, 

    getDefaultProps: function() { 
    return { 
     heading: 'this works', 
     items: [{ 
     href: '/', 
     label: ' - this does not - ', 
     }], 
    }; 
    }, 

    render: function() { 
    return (
     <div> 
     {this.props.item.map(function(item) { 
      return <Child {...item} /> 
     })} 
     </div> 
    ); 
    } 

}); 

var Child = React.createClass({ 

    propTypes: { 
    href: React.PropTypes.string, 
    label: React.PropTypes.string 
    }, 

    getDefaultProps: function() { 
    return { 
     href: '/', 
     label: ' - this does not - ' 
    }; 
    }, 

    render: function() { 
    return (
     <div /> 
     <p>href: {this.props.href}</p> 
     <p>label: {this.props.label} 
     </div> 
    ); 
    } 

}); 
Powiązane problemy