首页 文章

React - proptypes验证 - 返回错误不起作用但抛出确实[关闭]

提问于
浏览
1

所以,我正在查看react proptypes选项,我想检查子项是否是特定类型,它非常简单,如下所述:https://facebook.github.io/react/docs/reusable-components.html#prop-validation我应该返回一个Error对象而不是抛出 . 但是当我返回一个Error对象时,它不会打印到控制台,但如果我抛出一个Error对象,一切正常 .

propTypes对象:

const propTypes = {
        children: function(props, propName) {
            const children = props[propName];
            React.Children.forEach(children, (child) => {
                if (child.type !== Field) {
                    // doesnt work
                    return new Error('Error');
                }
                return;
            });
        }
    };

const propTypes = {
        children: function(props, propName) {
            const children = props[propName];
            React.Children.forEach(children, (child) => {
                if (child.type !== Field) {
                    // does work
                    throw new Error('Error');
                }
                return;
            });
        }
    };

我该怎么办?

1 回答

  • 2

    forEach 循环返回不会使封闭函数返回 . 你最好做的是使用简单的 for 循环或Array.prototype.some

    const propTypes = {
      children: function(props, propName) {
        const children = props[propName];
        const invalid = React.Children.some(children, child => child.type !== Field);
        if (invalid) {
          return new Error('Error');
        }
      }
    };
    

相关问题