2015-09-27 43 views
1

如何強制/驗證在Array prop(對React Component)中傳遞的每個項目是否爲特定的React類型?反應PropTypes。強制將數組設置爲特定的React類型

這裏是一個這樣的例子代碼:

<div id="container"></div> 

<script type="text/jsx"> 
    var MyButton = React.createClass({ 
     render: function() { 
      return (<input type="button" value={this.props.text} />); 
     } 
    }); 

    var MyButton2 = React.createClass({ 
     render: function() { 
      return (<input type="button" value={this.props.text} />); 
     } 
    }); 

var MyComp = React.createClass({ 
    propTypes: { 
     //buttons: React.PropTypes.arrayOf(MyButton) //Something like this 
    }, 
    render: function() { 
     return (<div><div>{this.props.title}</div> 
      {this.props.buttons} 
      </div> 
     ); 
    } 
}); 

var buttons = [React.createElement(MyButton, {key:"3", text: "Save"})]; 
buttons.push(React.createElement(MyButton, {key: "1",text: "Cancel"})); 
buttons.push(React.createElement(MyButton2, {key: "2",text: "Search"})); // And don't allow this one 

React.render(<MyComp title="My Window" buttons={buttons} />, document.getElementById('container')); 
</script> 

回答

1

this good article所示約propTypes,你可以寫一個可以傳遞給React.PropTypes.arrayOf自己的擴展功能。

這是在上述引用的電子郵件後示出的例子:

var emailPropType = function (props, propName, component) { 
    if (!isEmail(props[propName])) { 
    return new Error('Invalid email!'); 
    } 
}; 

可以這樣使用:

var EmailList = React.createClass({ 
    propTypes: { 
    emails: React.PropTypes.arrayOf(emailPropType).isRequired 
    }, 
    render: function() { 
    return React.DOM.ul(null, this.props.emails.map(function (email) { 
     return React.DOM.li({ key: email }, email); 
    })); 
    } 
}); 
相關問題