反应组件的渲染数组 [英] React render array of components

查看:51
本文介绍了反应组件的渲染数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问.有谁知道如何渲染组件数组?试图使开发人员更轻松地更改特定组件.(就像仪表板一样.)

Quick question. Anyone know how to render an array of components? Trying to make it easier for a developer to alter a particular component. (It's like a dashboard).

组件列表文件

import React from 'react';
export default [
    <ComponentOne/>
    <ComponentTwo/>
];

仪表板组件

import React from 'react';

import components from './../../components';

export default class Dashboard extends React.Component 
{
    render = () => {
        //Want to render the array of components here.
        return (
            <div className="tile is-parent">
                {components}
            </div>
        );
    };
}

问题是我需要向其中添加密钥的一系列组件.然而!我似乎也无法向该组件添加键,也不确定如何真正解释它,因此这是我尝试过的代码:

The issue is I have an array of components that I need to add a key to. However! I can't seem to add a key to the component as well, not sure how to explain it really so here's the code I've tried:

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

如果执行上述操作,我不会收到您必须应用密钥"错误,但是什么都没有呈现?我猜这是因为组件"不存在或沿这些思路很怪异.

If I do the above I get no 'you must apply a key' errors however nothing renders? And I'm guessing it's because 'component' doesn't exist or something weird along those lines.

我也尝试过 component.key = key; ,但是显然它不能让我在这种类型的Object上这样做吗?

I've also tried component.key = key; but it doesn't let me do that on this type of Object apparently?

我想我的后备方法是返回一个简写函数而不是一个数组,但是由于某种原因我喜欢该数组?对于大三学生来说似乎更简单.

My fallback I suppose is to return a shorthand function instead of an array but I like the array for some reason? Seems simpler for juniors.

推荐答案

您是否考虑过使用新的反应片段?(在v16中)

Have you consider using the new React Fragments? (in v16)

这将是最简单的解决方案,因为它会传递整个数组/密钥问题.

This would be the simplest solution as it would by pass the whole array/key issue.

如果您需要传递密钥,那么我建议您仅要求组件具有密钥.这就是React的工作方式,因此,我不建议您将这种行为隐藏在可能无法预测的界面后面.

If you need to pass key, then I'd suggest to simply require the components to have the keys. This is how React works, so I wouldn't suggest you to hide this behavior behind an interface that might not be predictable.

如果您确实需要执行此操作,则可以使用 React.cloneElement 来克隆元素并注入新属性:

If you really need to do this, then you can use React.cloneElement to clone the element and inject new properties:

React.cloneElement(element, { key: 'foo' });

这篇关于反应组件的渲染数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆