reactjs - v-for 在 react 中的等价物是什么?

标签 reactjs vue.js v-for duplicate-symbol

在 vue 中,我可以多次复制一个 svg 文件,例如 v-for="i in 5":key="i"。我如何在 React 中做到这一点?

<svg v-for="i in 5":key="i"  width="36px" height="35px" viewBox="0 0 36 35" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <!-- Generator: Sketch 49.3 (51167) - http://www.bohemiancoding.com/sketch -->
    <title>Star</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Profile-nav" transform="translate(-11.000000, -4.000000)" fill="#F8E71C" stroke="none" stroke-width="2">
            <g id="Group-2" transform="translate(0.000000, -1.000000)">
                <polygon id="Star" points="29 32.8753882 19.595436 38 21.3915479 27.145898 13.7830957 19.4589803 24.297718 17.8753882 29 8 33.702282 17.8753882 44.2169043 19.4589803 36.6084521 27.145898 38.404564 38"></polygon>
            </g>
        </g>
    </g>
</svg>

最佳答案

您的操作方式与在 JavaScript 中创建数组的方式非常相似。一种选择是使用带有长度的 Array.from,并使用映射器函数中的第二个参数作为索引,例如:

Array.from({ length: 5 }, (_, i) => (
  <svg key={i}>
    // ...
  </svg>
));

const App = () => (
  Array.from({ length: 5 }, (_, i) => (
    <svg key={i} width="36px" height="35px" viewBox="0 0 36 35" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <title>Star</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="Profile-nav" transform="translate(-11.000000, -4.000000)" fill="#F8E71C" stroke="none" stroke-width="2">
            <g id="Group-2" transform="translate(0.000000, -1.000000)">
                <polygon id="Star" points="29 32.8753882 19.595436 38 21.3915479 27.145898 13.7830957 19.4589803 24.297718 17.8753882 29 8 33.702282 17.8753882 44.2169043 19.4589803 36.6084521 27.145898 38.404564 38"></polygon>
            </g>
        </g>
    </g>
    </svg>
  ))
);

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

关于reactjs - v-for 在 react 中的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65692188/

相关文章:

ReactJS componentWillUnmount 未在路由更改时调用

reactjs - 如何在没有Link的情况下触发react-router

php - REACT + PHP - 仅在 POST 请求中阻止了我的 CORS 策略

svg - vue svg 路径与 v-for

javascript - 根据键值从 v-for 返回单个结果

javascript - Vue.js 组件中的 V-for 不起作用

javascript - 我正在尝试将产品列表的数量限制为 10

javascript - 将新项目附加到 Vue 2 中的列表

javascript - 使用命名空间模块中的 mapState 和 mapMutations

javascript - Ajax 请求未提供任何数据