【问题标题】:How to use 2 higher-order components at the same time? (in order to use injectIntl from react-intl)如何同时使用 2 个高阶组件? (为了使用 react-intl 中的 injectIntl​​)
【发布时间】:2019-04-23 14:27:43
【问题描述】:

我知道为了使用 react-intl 库中的 injectIntl​​,我需要类似的东西:

export default injectIntl(SectionNavbars)

但是我已经在使用 withStyles 高阶组件,如何将两者结合起来?

import React from 'react'
/* more stuff */
import { injectIntl } from 'react-intl'

class SectionNavbars extends React.Component {

  render() {
    const { classes } = this.props;
    const { intl } = this.props;
    return (

      <div className={classes.section}>
        <Header
          brand={ <img src={logo}/> }
          rightLinks={
              <ListItem className={classes.listItem}>
                <CustomDropdown
                        buttonText={intl.formatMessage({ id: 'products' })}
                        buttonProps={{
                          className: classes.navLink,
                        }}
                        dropdownList={[
                         /*stuff*/
                        ]}
                      />
              </ListItem>
          }
        />
      </div>
   );
  }
}

export default withStyles(navbarsStyle)(SectionNavbars);

【问题讨论】:

    标签: javascript reactjs react-intl


    【解决方案1】:

    你可以像这样组合 HOC injectIntl(withStyles(navbarsStyle)(SectionNavbars))

    或者更好

    1. 您可以使用来自recompose librarycompose
    2. 其他函数式编程助手,如来自lodashflowflowRight

    另外,我建议您阅读 recompose 文档,它确实有助于理解 HOC 并提供非常有用的东西。

    【讨论】:

    • injectIntl​​(withStyles(navbarsStyle)(SectionNavbars)) 工作正常,谢谢!当我在这里时,我可能会问为什么使用 recompose 库会更好?
    • 两个原因: 1. 更好地组织代码。它更容易阅读和编辑。在您的情况下,只有两个功能,但可能更多。 2.重构的知识可以为你节省很多时间。在其他 HOC 中,我特别建议您仔细查看 withStateHandlers()withPropsOnChange()。将“纯”组件以及所有状态和逻辑封装到使用 compose 组织的 HOC 中是一种非常好的做法。
    猜你喜欢
    • 2019-07-29
    • 2019-08-10
    • 2020-08-24
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2017-09-26
    • 2018-11-18
    • 1970-01-01
    相关资源
    最近更新 更多