我想在一个元素之前添加一个随机的字符数量,重复这个元素20次,在每次之前添加一个不同的字符数量。例如:
function App() {
return (
<>
Hello World! This is time {i}
// I want to add a random amount of spaces before the h1 tags above. I also want to repeat that h1 tags 20 times with a different amount of spaces before each h1 tag
</>
)
}我想要返回的例子是
你好,世界!这是第一次
大家好,世界!这是时间2
可发性的中转站-你好世界!这是第三次
更贴心的人你好世界!这是第四次
………
每一个都有不同的空间。
发布于 2020-12-09 23:28:11
function HeaderWithLeadingSpacing({ maxSpacing = 20, num }) {
const rdn = Math.round(Math.random() * maxSpacing);
const spacing = Array.from(Array(rdn), () => '\u00A0');
return (
<h1>{spacing}Hello World! This is number {num}</h1>
)
}
function App() {
return Array.from(Array(20), (_, i) => (
<HeaderWithLeadingSpacing
maxSpacing={10}
num={i + 1}
/>
));
}
ReactDOM.render(<App />, document.getElementById('app'))<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
如果我的理解是正确的,那么上面的代码就能做到这一点。
https://stackoverflow.com/questions/65226243
复制相似问题