我正在尝试渲染一组命名的反应组件,例如<Foo />、<Bar />和<Baz />。
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>
);
Run Code Online (Sandbox Code Playgroud)
我可以迭代我的数组并在控制台中查看元素数组,但它们被渲染为空的 html 元素“ <foo></foo><bar></bar><baz></baz>”,而不是实际的组件。为什么会发生这种情况,更重要的是,我怎样才能渲染组件?
item.type您应该像这样使用组件而不是字符串
import Foo from './Foo';
import Bar from './Bar';
[ { type: Foo, }, { type: Bar, }, { type: Baz}]
Run Code Online (Sandbox Code Playgroud)
更新:
如果您事先没有组件引用,则使用映射对象将字符串转换为组件引用,如下所示
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} />);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23129 次 |
| 最近记录: |