我有以下代码为一个组件渲染 5 颗星。我希望它始终正好是 5 星,但根据评级,其余的星应该是空白的。我有以下代码来实现这一点。:
const stars = []
for (let i = 0; i < 5; i++){
if (i < Math.floor(rating)){
stars.push(<span className="feedback-star full"></span>)
} else {
stars.push(<span className="feedback-star blank"></span>)
}
}
React 说我应该为每个跨度设置一个唯一的关键 Prop 。应该如何有效地实现这一点? (我想我可以使用 new Date() 或 Math.random(),但在超过 100 个反馈的列表上,每个 5 星,这不会是很多不必要的操作吗?)
最佳答案
您阅读了 React 中的键以及如何有效地使用它们。你可能会发现 this post有用。基本上:
React uses the key prop to understand the component-to-DOM Element relation which is then used for the reconciliation process. It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one.
话虽这么说,要解决你的问题,试试这个:
let stars = []
for (let i = 0; i < 5; i++){
if (i < Math.floor(rating)){
stars.push(<span key={i} className="feedback-star full"></span>)
} else {
stars.push(<span key={i} className="feedback-star blank"></span>)
}
}
对于更短的语法,您还可以这样做:
let stars = []
for (let i = 0; i < 5; i++){
stars.push(<span key={i} className={"feedback-star " + (i < Math.floor(rating) ? "full" : "blank")}></span>)
}
另请注意,使用 const
时,您正在创建一个对变量的只读引用,并且不得改变它。对于这种情况,请改用 let
。
关于javascript - 评级明星列表的好关键 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130122/