【问题标题】:How to dynamically generate id for function components?如何动态生成功能组件的id?
【发布时间】:2021-11-30 22:42:24
【问题描述】:

您好,我正在使用 React 创建我的第一个应用程序。该应用程序生成 css 样式。它由边框半径、盒子阴影等组件组成。这些组件可以相互组合。每个组件的变量通过 redux 发送到一个数组,然后渲染。我想增加选择任何组件并将它们相互组合的可能性。我的问题是组件 ID。我不知道如何根据组件顺序动态生成 id。我需要它来更新 redux 中的数组。那里会有一个删除任何组件的选项,所以我不能静态输入。我尝试使用 map() 来实现,但每个组件都有不同的名称,我不知道该怎么做。有没有可能?

在此先感谢,对不起我的英语

const components = [<Transform id={0} />, <BorderRadius id={1} />];
const renderComponents = components.map((component, index) => component);

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    我不建议您映射不同的组件,但如果您确实需要,请将其包装在这样的片段中。

    const components = [<Transform />, <BorderRadius />];
    const renderComponents = components.map((component, index) => (
      <React.Fragment id={index}>
       {component}
      </React.Fragment>
    ));
    

    在此处查看有关片段的更多信息

    https://reactjs.org/docs/fragments.html

    【讨论】:

      猜你喜欢
      • 2013-04-22
      • 2013-03-01
      • 2018-07-12
      • 1970-01-01
      • 2019-07-17
      • 2018-09-24
      • 2021-05-09
      • 2013-03-06
      • 2011-12-08
      相关资源
      最近更新 更多