【问题标题】:Is it possible to pass a string array as parameter using HOC?是否可以使用 HOC 将字符串数组作为参数传递?
【发布时间】:2019-06-09 21:10:40
【问题描述】:

我在 nextJS 应用程序中使用一些 HOC 组件通过getInitialProps 设置一些道具值。 但我需要为这些道具使用动态值。

在我的索引组件中,我调用了withServerProps。是否可以将一些字符串数组传递给它?

index.js

import React, { Component } from 'react'
import { withTranslation } from 'i18n'
import withServerProps from 'with-server-props'

class Index extends Component {
  render () {
    return (<div>Some content</div>)
  }
}

export default withServerProps( // <-- How to pass an array with strings?
  withTranslation()(Index) 
)

我需要在这个函数中获取字符串数组:

with-server-props.js

import React, { Component } from 'react'

export default WrappedComponent =>
  class extends Component {
    static async getInitialProps (context) {
      const { query } = context
      return {
        id: query && query.id
        target: PASSED_ARRAY // <-- Need to recieve the array here
      }
    }
    render () {
      return <WrappedComponent {...this.props} />
    }
  }

【问题讨论】:

    标签: javascript reactjs high-order-component


    【解决方案1】:

    是的,你绝对可以。只需在 index.js 中导出期间添加一些参数即可。

    export default withServerProps(withTranslation()(Index), ["hello"])
    

    然后在你的 HOC 中:

    export default function handleServerProps(WrappedComponent, arr) {
      class Hoc extends Component {
        static async getInitialProps (context) {
          const { query } = context
          return {
            id: query && query.id,
            target: arr,
          }
        }
        render () {
          return <WrappedComponent {...this.props} />
        }
      }
    
      return Hoc;
    }
    

    【讨论】:

    • 我确实收到了错误The default export is not a React Component
    • 啊,是的,你需要在函数中返回它
    猜你喜欢
    • 2012-06-05
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2017-06-14
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多