我似乎有一個非常奇怪的問題,即組件映射似乎忽略了它們的屬性(盡管console.log()證明各個屬性值確實到達了組件)。
我正在使用物件串列生成多個相同的組件。每個物件都有兩個引數,一個“名稱”和一個“評級”(一個從 0.0 到 1.0 的值)。這一切都在已宣告為類 而非函式的組件中處理。
categories = [
{name: "Name1", rating: 0.5},
{name: "Name2", rating: 1.0},
{name: "Name3", rating: 0.6},
{name: "Name4", rating: 1.0},
{name: "Name5", rating: 0.4}
]
...
render = () =>{
{this.categories.map(c => <StarCard name={c.name} rating={c.rating}/>)}
}
串列的元素被映射到自定義StarCard組件,分別傳入每個串列條目的名稱和評級。
在StarCard接著傳到只是rating值到一個Star組件,它負責繪制在螢屏上的星形的SVG圖形,與同時用于填充星到某一點的掩模,基于它的評級(完全排空= 0.0,完全滿- 1.0)。
const StarSVG = ({classProps, rating}) => {
const starFill = parseInt(23.0-(23.0*Number(rating)));
const num = 13;
//console.log(typeof starFill " " typeof num);
//console.log(starFill);
return(
<svg xmlns="http://www.w3.org/2000/svg" className={classProps} width="24" height="24" viewBox="0 0 24 24">
<defs>
<clipPath id="starClip">
<rect x="0" y={starFill} width="200" height="200" />
</clipPath>
</defs>
<path clipPath="url(#starClip)" d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 1.48 8.279-7.416-3.967-7.417 3.967 1.481-8.279-6.064-5.828 8.332-1.151z"/>
</svg>
);
}
export default StarSVG;
如您所見,我正在計算 rating 道具的值,以計算用于隱藏圖形頂部的遮罩的 Y 位置。然而,出于某種原因,該星的所有實體在其各自的組件中,僅繼承串列中第一個物件的評級值。例如,如果第一個值設定0.5為如第一個片段所示,螢屏上的所有星星將被填充一半,并完全忽略它們自己的評級值(盡管控制臺日志證明評級值計算正確)。
我不知道是什么原因造成的。我曾嘗試更改使函式 avar而不是 a const(與函式內的變數相同),但似乎無法解決該問題。
感謝您走到這一步,非常感謝任何幫助!如果您需要其他資訊,請隨時發表評論。
uj5u.com熱心網友回復:
所以這就是你 StarCard 的樣子
const StarSVG = ({ classProps, rating, name }) => {
const starFill = parseInt(23.0 - 23.0 * Number(rating));
//console.log(typeof starFill " " typeof num);
console.log(starFill);
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={classProps}
width="24"
height="24"
viewBox="0 0 24 24"
>
<defs>
<clipPath id={name}>
<rect x="0" y={starFill} width="24" height="24" />
</clipPath>
</defs>
<path
clipPath={`url(#${name})`}
d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 1.48 8.279-7.416-3.967-7.417 3.967 1.481-8.279-6.064-5.828 8.332-1.151z"
/>
</svg>
);
};
export default StarSVG;
請注意,clipPath id 應該是唯一的,因此我們為此使用了名稱
<clipPath id={name}>
<rect x="0" y={starFill} width="24" height="24" />
</clipPath>
并確保在元素中參考它
> <path
> clipPath={`url(#${name})`}
> d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 1.48 8.279-7.416-3.967-7.417
> 3.967 1.481-8.279-6.064-5.828 8.332-1.151z" />
確保在你的主要組件中添加一個鍵到 StarSVG
<div style={{ margin: "10rem" }}>
{categories.map((c) => (
<StarSVG name={c.name} rating={c.rating} key={c.name} />
))}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369748.html
標籤:javascript 反应
上一篇:如何在用戶完成任務之前鎖定內容?
