1

如何强制/验证传入的 Array 道具(到 React 组件)的每个项目都属于特定的 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>
4

1 回答 1

1

如这篇关于 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);
    }));
  }
});
于 2015-09-27T17:59:45.140 回答