2017-10-06 34 views
0

我用我的反應組件創建了npm包。 babel預設es2015並作出反應使用React組件|創建npm包component.type不明確

在我的組件中,我帶着所有的孩子並檢查他們的類型(執行特定操作)。但是所有的孩子都有類型==未定義。 當組件直接在我的項目中(不是從npm包安裝的),所有東西都可以正常工作。

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

回答

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

希望它可以幫助

+0

部分是有益的。 我的組件可以有幾個不同的子組件,我必須知道第一個孩子是Type1,第二個孩子是Type4。我遇到的問題是,webpack將我的組件轉換爲npm包,將所有類Component1都擴展爲React.Component。 – massther

+0

請問您可以添加webpack配置文件嗎?謝謝! – NickHTTPS

相關問題