1

在 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>
4

2 回答 2

4

您将采用与在 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>

于 2021-01-12T21:21:14.783 回答
1

你可以使用`

[...Array(5)].map((_,i)=>{
           return  <svg key={i} ...>
                    ...
                 </svg>
  })

并用 camelCase 替换 kebab-case 属性:

stroke-width ---> strokeWidth
fill-rule ---> fillRule
于 2021-01-12T21:32:13.600 回答