如何呈现JSX元素数组(反应组件) [英] How to render an array of JSX elements (React components)
问题描述
我正在尝试渲染一组命名的React组件,例如<Foo />
,<Bar />
和<Baz />
.
I'm trying to render an array of named react components, say <Foo />
, <Bar />
, and <Baz />
,for example.
const rendered = [];
const getItems = this.props.itemslist.map((item, key) => {
const TYPE = item.type;
rendered.push(<TYPE data-attributes={attributes} key={key} />);
});
return (
<Grid>
<Row>
{rendered}
</Row>
</Grid>
);
我可以遍历数组,并在控制台中看到元素数组,但是它们呈现为空的html元素"<foo></foo><bar></bar><baz></baz>
",而不是实际的组件.
为什么会发生这种情况,更重要的是,如何获得要渲染的组件?
I can iterate over my array and see in the console the array of elements, but they are rendered as empty html elements "<foo></foo><bar></bar><baz></baz>
", and not the actual components.
Why is this happening and, more importantly, how can I get the COMPONENTS to render?
推荐答案
您应该像这样在item.type
中使用component而不是字符串
You should use component instead of string in item.type
like this
import Foo from './Foo';
import Bar from './Bar';
[ { type: Foo, }, { type: Bar, }, { type: Baz}]
更新:
如果您事先没有组件引用,请使用一个映射对象,将您的字符串转换为这样的组件引用
If you do not have component reference in advance then use a mapping object which convert your string to component reference like this
import Foo from './Foo';
import Bar from './Bar';
const mapper = {
Foo: Foo,
Bar: Bar,
}
// Then use it like this
const getItems = this.props.itemslist.map((item, key) => {
const Type = mapper[item.type];
rendered.push(<Type data-attributes={attributes} key={key} />);
});
这篇关于如何呈现JSX元素数组(反应组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!