【问题标题】:Passing an array of Components as a Props in React在 React 中将组件数组作为 Props 传递
【发布时间】:2019-06-04 21:10:50
【问题描述】:

我正在寻找一种将组件数组传递给选项卡组件的道具的方法。只是想知道这是否可能。

所以我需要创建一个组件来缩短材质 ui 的 tabbing 方法,但是我找不到将组件数组作为 prop 传递的方法,以便在该组件上呈现它。

这是我的代码示例:

<FullWidthTab
components = [<Component1/>, <Component2/>] //this is where components renders
 menuLabels = ['Menu1', 'Menu2'] //this is where title render
/>

我像这样将它们映射到我的代码上,我使用了 lodash map 方法:

map(components, component=>{

 <TabContainer>{component}</TabContainer>

}

但它会返回这个。 警告:react-swipeable-view:提供的孩子之一无效:null。 我们期待一个有效的 React 元素

当我 console.log 它返回的组件时: {$$typeof: Symbol(react.element), type: ƒ, key: null, ref: null, props: {…}} Object 需要帮助

我希望它可以渲染组件。

【问题讨论】:

  • 你有解决办法吗?

标签: reactjs material-ui


【解决方案1】:

组件的名称必须以大写字母开头,但我可以在这里看到components = [&lt;component1/&gt;, &lt;component2/&gt;] 他们不是。所以你必须将[&lt;component1/&gt;, &lt;component2/&gt;] 转换为[&lt;Component1/&gt;, &lt;Component2/&gt;]。第二件事我看到你的map 语法很奇怪,一定是这样的:

components.map(component => (<TabContainer>{component}</TabContainer>))

参考:https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

【讨论】:

  • 谢谢,但还是不行,顺便说一句,我使用了 lodash 的地图方法我已经编辑了我的帖子
【解决方案2】:

我用另一个实现解决了这个问题。

我使用了“react-swipeable-views”,而是传递了一个我使用过的组件

       <SwipeableViews
            axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
            index={this.state.value}
            onChangeIndex={this.handleChangeIndex}
        >
            { children }
        </SwipeableViews>

并且改变了:

<FullWidthTab
components = [<Component1/>, <Component2/>] //this is where components renders
 menuLabels = ['Menu1', 'Menu2'] //this is where title render
/>

<FullWidthTab
 components = [<Component1/>, <Component2/>] //this is where components renders
 menuLabels = ['Menu1', 'Menu2'] //this is where title render
>
  <Component1/>
  <Component2/>
</FullWidthTab>

但是如果你能知道如何通过 props 传递组件那就太好了!

【讨论】:

    【解决方案3】:

    因为你需要在地图中返回一个值。

    map(components, component=>{
    
     return <TabContainer>{component}</TabContainer>
    
    }
    

    【讨论】:

    • 我在组件的渲染中这样做了。 return 可以省略。
    【解决方案4】:

    您的 es6 语法需要进行细微调整才能返回 react 组件。

    map(components, component => <TabContainer>{component}</TabContainer> )
    

    或者,如果您可以使用数组中的 map 函数而不是从库中导入。

    components.map( component => <TabContainer>{component}</TabContainer> )
    

    【讨论】:

    • 哦,我忘了我用了 lodash 的地图
    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 2021-06-16
    • 2019-09-11
    • 2017-09-14
    • 2017-02-13
    • 1970-01-01
    相关资源
    最近更新 更多