如何渲染一系列JSX元素(React组件)



我正在尝试渲染一系列命名的react组件,例如 <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>
);

我可以在数组上迭代,并在控制台中看到元素的数组,但它们被呈现为空的HTML元素" <foo></foo><bar></bar><baz></baz>",而不是实际的组件。为什么会发生这种情况,更重要的是,我该如何使组件呈现?

您应该在 item.type中使用组件而不是字符串

import Foo from './Foo';
import Bar from './Bar';
[ { type: Foo, }, { type: Bar, }, { type: Baz}]

更新:

如果您没有事先参考的组件参考,请使用将字符串转换为组件参考的映射对象

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} />);
});

第一个错误是查看.map的不正确使用。请记住,.map遍历每个数组元素并更改它们。现在,您正在使用它,就好像是.forEach

您的代码应该更像是这样:

const getItems = this.props.itemslist.map((item, key) => {
  const TYPE = item.type;
  return <TYPE data-attributes={attributes} key={key} />
});

您可以使用React.createElement用动态名称创建React元素。还要确保导入这些组件。

const rendered = [];
const getItems = this.props.itemslist.map((item, key) => {
    const component = React.createElement(item.type, {data-attributes: attributes, key: key}, null);
    rendered.push(component);
});
return (
  <Grid>
    <Row>
    {rendered}
    </Row>
  </Grid>
);

最新更新