2017-04-02 111 views
3

我試圖做類似下面的,但它返回null:您可以使用React Components的es6導入別名語法嗎?

import { Button as styledButton } from 'component-library' 

然後試圖呈現爲:

import React, { PropTypes } from "react"; 
import cx from 'classNames'; 

import { Button as styledButton } from 'component-library'; 

export default class Button extends React.Component { 
    constructor(props){ 
     super(props) 
    } 
    render() { 
     return (
       <styledButton {...this.props}></styledButton> 
     ) 
    } 
} 

的原因是,我需要進口Button組件從庫中導出,並導出包含相同名稱的包裝組件,但維護導入組件的功能。如果我把它留在import { Button } from component library那麼當然,我得到一個多重聲明錯誤。

任何想法?

+1

爲什麼你不能改變類按鈕名稱? – Ved

+2

React組件應該以大寫字母開頭:不使用'styledButton',而是使用'StyledButton' – topheman

+0

@Ved我正在使用react-styleguidist來顯示每個組件,並且需要將所有組件包裝到組件庫中。如果我更改類Button的名稱,show code將爲操場中的每個組件命名。 –

回答

7

您的語法是有效的。 JSX是React.createElement(type)的語法糖,只要type是一個有效的React類型,它就可以在JSX「tags」中使用。如果Button爲空,則導入不正確。也許按鈕是組件庫的默認導出。嘗試:

import {default as StyledButton} from "component-library"; 
+0

嗯,似乎沒有工作; 按鈕被定義在他的庫中: '''從'react-atlas-core'導入{ButtonCore}; 從'react-atlas-default-theme'導入{ButtonStyle}; export const Button = CSSModules(ButtonCore,ButtonStyle,{allowMultiple:true}); ''' –

+0

不使用默認導出;所以我不知道爲什麼它不會返回任何東西。 –

+0

我可能會重新評估你認爲會出錯,因爲該語法和你的意圖是有效的。你得到的錯誤究竟是什麼? – chris

2

不知道爲什麼我無法導入別名;

作爲工作的時候,我終於實現了這一點:

import React, { PropTypes } from "react"; 
import * as StyledLibrary from 'component-library'; 

export default class Button extends React.Component { 
    constructor(props){ 
     super(props) 
    } 
    render() { 
     return (
      <StyledLibrary.Button {...this.props}></StyledLibrary.Button> 
     ) 
    } 
} 

感謝所有