简体   繁体   English

我想重复“★”和React状态中的数字一样多

[英]I want to repeat “★” as many times as a number in state in React

I want to repeat "★" as many times as a number in state in React. 我想在React中重复“★”和状态数字一样多的次数。

What should I do? 我该怎么办?

I want to printing like this. 我想这样打印。

js ★★★ JS★★★
ts ★★ ts★★
html ★★★ HTML★★★

 state = { myScores: [ { name: "js", score: 3 }, { name: "ts", score: 2 }, { name: "html", score: 3 } ] } ... const myScores = this.state.myScores.map( ({name, score}) => ( <div> {name} { for(let i=0; i<score; i++) { <div>★</div> } } </div> ) ); 
 <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> 

All you need to do is replace for loop with. 您需要做的就是替换循环。

<div>{"★".repeat(score)}</div>

Reason why your code was not working the way you expected is. 代码未按预期方式工作的原因是。

  1. In practice the OP's code will throw an error since you cannot have JavaScript statements inside JSX (ie it won't render anything). 在实践中,OP的代码将引发错误,因为JSX中不能包含JavaScript语句(即,它不会呈现任何内容)。 very well explained by @FelixKling in comments. @FelixKling在评论中对此进行了很好的解释。
  2. Since while iterating through for loop you're adding a new div every time which is a block element.so it will take up the complete width. 因为在遍历for循环时您每次都会添加一个新的div,它是一个块元素,所以它将占用整个宽度。 you can read more about block elements here https://www.w3schools.com/html/html_blocks.asp 您可以在此处阅读有关块元素的更多信息https://www.w3schools.com/html/html_blocks.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM