2017-04-02 113 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> 
     ) 
    } 
} 

感谢所有