2016-06-30 14 views
14

Esiste un modo in React per fornire puntelli predefiniti a una matrice nidificata di elementi di una determinata forma?Come si forniscono puntelli predefiniti per la forma annidata in React?

Dato l'esempio di seguito, è possibile vedere il mio primo tentativo, tuttavia ciò non funziona come previsto.

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 - ', 
    }], 
}; 

In questo esempio, mi sarei aspettato il seguente:

// 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 - ' }, 
    ] 
}; 

risposta

14

No. puntelli predefiniti sono solo superficialmente uniti.

Tuttavia, un approccio potrebbe essere quello di avere un componente figlio per ciascun elemento. In questo modo, ogni componente Bambino riceve un oggetto dall'array item e quindi i puntelli predefiniti verranno uniti come previsto.

Ad esempio:

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

});