【问题标题】:React.js: How can I render a single component from an array?React.js:如何从数组中渲染单个组件?
【发布时间】:2017-09-11 07:00:52
【问题描述】:

我有一个包含名为“componentPack”的组件的数组。我试图弄清楚如何根据数组中的索引来渲染某个组件。给我带来麻烦的部分是在 JSX 中渲染该组件。为了解决这个问题,我使用了一个名为“stager”的中间数组,我将一个组件推送到该数组,然后从中映射:

var comp = stager.map((Component) => {
  return <Component />;
});

是否可以直接从原始数组中选择一个组件?

类似:

var comp = () => {return <{componentPack[3][2]} />;}

我觉得我并不真正理解 JSX 在这种情况下是如何工作的。非常感谢任何帮助。

【问题讨论】:

    标签: arrays reactjs components


    【解决方案1】:

    您可以从地图组件中选择条件渲染,例如

    var index = 3;
    const component = componentPack.map((Component, idx) => {
        if(idx === index) {
             return <Component/>
        } else {
             return null;
        }
    })
    

    那么你可以像这样渲染它

    render() {
        return (<div>{component}</div>);
    }
    

    【讨论】:

      【解决方案2】:

      您可以直接引用 jsx 对象。例如,如果您的 componentPack 是一个组件数组,如下所示:

      const componentPack = [1, 2, 3, 4, 5].map((item) =>
        <Component/>
      );
      

      您可以引用任何单个元素并获取特定组件,例如:

      render(){
        return componentPack[2] //Will return the third Component
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-28
        • 2021-02-06
        • 2017-08-20
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 2022-07-30
        • 2020-05-14
        相关资源
        最近更新 更多