React.JS & JSX map渲染组件仅继承列表首项rating属性值问题
问题原因
问题本质是SVG的id属性全局唯一特性导致的。你所有StarSVG组件中定义的clipPath都使用了固定的id="starClip",而HTML页面中id是全局生效的,浏览器碰到重复id时只会识别第一个出现的id对应的元素,所以所有星星的clipPath="url(#starClip)"都会调用第一个StarSVG组件定义的遮罩,最终表现就是所有星星填充效果和第一个完全一致。
解决方法
给每个StarSVG组件的clipPath生成唯一的id即可,你可以从上层组件把每个分类的唯一标识(比如name、map对应的index)传进StarSVG,拼接成唯一id:
首先修改StarSVG组件代码,接收唯一标识参数:
const StarSVG = ({classProps, rating, uniqueKey}) => { const starFill = parseInt(23.0-(23.0*Number(rating))); // 拼接唯一的clipPath id const clipId = `starClip-${uniqueKey}` return( <svg xmlns="http://www.w3.org/2000/svg" className={classProps} width="24" height="24" viewBox="0 0 24 24"> <defs> <clipPath id={clipId}> <rect x="0" y={starFill} width="200" height="200" /> </clipPath> </defs> <path clipPath={`url(#${clipId})`} 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;
然后在调用StarSVG的位置传入唯一标识,比如用每个分类的name作为唯一值:
// StarCard组件内部调用StarSVG的位置 <StarSVG classProps="你的自定义类名" rating={rating} uniqueKey={name}/>
内容的提问来源于stack exchange,提问作者Sean Preston
相关产品推荐
相关产品推荐

