是否可以使用HOC将字符串数组作为参数传递?

时间:2019-06-09 21:10:40

标签: javascript reactjs high-order-component

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

在索引组件中,我正在调用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} />
    }
  }

1 个答案:

答案 0 :(得分: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;
}
相关问题