【问题标题】:How to render an array of JSX elements (React components)如何渲染 JSX 元素数组(React 组件)
【发布时间】:2018-03-07 11:07:36
【问题描述】:

我正在尝试渲染一组命名的 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 元素“&lt;foo&gt;&lt;/foo&gt;&lt;bar&gt;&lt;/bar&gt;&lt;baz&gt;&lt;/baz&gt;”,而不是实际的组件。 为什么会发生这种情况,更重要的是,如何让 COMPONENTS 进行渲染?

【问题讨论】:

  • 是的,它是一个字符串:
  • @brainstormtrooper 不要将字符串存储在item.type 中。而是存储组件本身。
  • itemslist: [ { type: 'Foo', }, { type: 'Bar', }, { type: 'Baz', }, ]
  • @Prakashsharma,我该怎么做?我在 javascript 中有一个配置文件...我需要能够迭代和配置我的组件...

标签: reactjs redux jsx


【解决方案1】:

您应该像这样在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} />);
});

【讨论】:

【解决方案2】:

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

您的代码应该看起来更像这样:

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

【讨论】:

    【解决方案3】:

    您可以使用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>
    );
    

    【讨论】:

    • 谢谢。我试过了,但我得到了相同的结果:-(
    • 你是不是以大写字符开头的字符串,否则它不会被视为反应组件
    猜你喜欢
    • 2021-12-07
    • 2021-11-09
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    相关资源
    最近更新 更多