使用更高阶的组件装饰导入的React组件

时间:2016-08-05 21:39:54

标签: javascript reactjs decorator

我知道如何在导出之前装饰组件,如下所示:

export default ButtonDecorator(MainButton)

但是如果我尝试制作一个索引来导入它并在某些情况下以不同的方式装饰它。它不会工作。

以下是索引的示例:

import MainButton from './main/main_button'
import BackButton from './back/back_button'

import { ButtonDecorator, LinkDecorator } from 'decorators'

export {
    ButtonDecorator(MainButton) as MainButton,
    LinkDecorator(MainButton) as MainHrefButton,
    BackButton
}

更高阶的组件:

import React, { Component } from 'react'

let Btn = InnerComponent => {
    class NewBtn extends Component {

        constructor(props) {
            super(props)
        }

        render() {
                return (
                    <button onClick={this.props.onClick}>
                        <InnerComponent disabled={this.props.disabled} />
                    </button>
                )
        }
    }

    return NewBtn
}

export default Btn

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

据我所知export需要名称(变量),而不是函数调用。试试这个:

const ButtonDecoratedMainButton = ButtonDecorator(MainButton);
const LinkDecoratedMainButton = LinkDecorator(MainButton);

export {
    DecoratedMainButton as MainButton,
    LinkDecoratedMainButton as MainHrefButton,
    BackButton
}