使用具有多个组件的React的高阶组件作为参数

时间:2017-11-22 06:34:52

标签: reactjs react-native

我很反应原生(和React为此目的),我刚刚开始使用高阶组件。我知道这些应该将一个组件作为参数返回一个其他组件。

我的问题是,我希望我的HOC()函数采用多个参数,即HOC:: C: React.Component, D: React.Component => H: React.Component(类似于Haskell的语法)。

现在,问题(以及我发布此内容的原因)是,它让我感觉我的代码有点笨重,因为我必须传递道具的方式。我最终做的是一个函数采用两个数组,第一个组件数组和第二个组件,必须以相同的顺序给出。 (以便propList[i]是组件props的{​​{1}}对象。)

类似的东西(假设完成所有导入):

componentList[i]

我已经设法建立了这样的东西,它适用于我想要的东西,但这个问题更多的是:

  • 这是件坏事吗?(我觉得这会伤害作曲,因为道具是在不同的地方指定的,例如)
  • 如果是的话,你会做什么呢?(我考虑过currying但我不知道如何实现它,特别是如果class MyComponent extends React.Component { render() { return <Text>{this.props.name}</Text> } } const HOC = (componentList, propsList) => class extends React.Component { render() { return( <View> {componentList.map( (Component, index) => { return <Component {...propsList[index]} /> })} </View> ) } } class App extends React.Component { render (){ //this call is what makes me uncomfortable const DoubleComponent = HOC([MyComponent, MyComponent],[{name: 'first'}, {name: 'second'}]); return( <DoubleComponent /> ) } } 必须采取任意数量的组件)

我也在追求你们可以给我的任何“良好做法提示”!

1 个答案:

答案 0 :(得分:2)

propsHOC可以直接从组件道具中获取的内容

const HOC = (componentList) =>

    class extends React.Component {
      render() {
        return(
          <View>
            {componentList.map( (Component, index) => {
              return <Component {...this.props[index]} />
            })}
          </View>
        )
      }

}
class App extends React.Component {
  render (){
    //this call is what makes me uncomfortable
    const DoubleComponent = HOC([MyComponent, MyComponent]); 
    return(
      <DoubleComponent names={[{name: 'first'}, {name: 'second'}]}/>
    )
  }
}