使用React组件创建npm包component.type未定义

时间:2017-10-06 12:13:55

标签: reactjs npm

我用反应组件创建了npm包。 babel预设es2015并做出反应

在我的组件中,我带走所有孩子并检查他们的类型(执行特定的操作)。但是所有的孩子都有类型== undefined。 当组件直接在我的项目中(不是从npm pack安装)时,每个方法都可以正常工作。

React.Children.forEach(this.props.children, function (child) {
        if (child.type === SomeChildComponent) { // <-- issue is here, from npm pack child.type is undefined
            defs = React.Children.map(child.props.children, c => c.props);
        }
    });

1 个答案:

答案 0 :(得分:0)

您可以使用自定义propType函数来验证子项:

static propTypes = {

  children: (props, propName, componentName) => {
    const prop = props[propName];
    return React.Children.forEach(prop, child => {
      if (child.type !== SomeChildComponent) {
        error = new Error(`${componentName} children should be of type ${SomeChildComponent}.`);
      }
    });
  }
}

希望有所帮助