2024年04月01日 建站教程
reactjs如何实现一个五星评价功能,下面web建站小编给大家详细介绍一下!
js组件代码:
import React,{Component} from 'react'class Star extends Component{ constructor(props){ super(props); this.state={ starNum:['star0','star0','star0','star0','star0'] //设置默认背景图 } } componentDidMount(){ //将传过来的类似7.3数字进行四舍五入再除2,得到的是类似2,3.5,6这种值 this.getStar(Math.round(this.props.star)/2+1); } getStar(num){ let newStar = this.state.starNum.map((item)=>{ //当num=3.5时遍历后newStar数组变成['star2','star2','star2','star1','star0','star0'] --num; return num>=1?'star2':((num>0)?'star1':'star0'); //两次三目运算 }) this.setState({ starNum:newStar //设置state为遍历后的新数组 }) } render(){ return (<span className="star"> { this.state.starNum.map((item, index)=>{ return <span className={item} key={index}></span> }) }</span>)} } export default Star;
css代码:
.star{ display: inline-block; } .star>span{ display: inline-block; width: 10px; height: 10px; background-size: 10px 10px; } .star0{ background-image: url(img/star0.png); } .star1{ background-image: url(img/star1.png); } .star2{ background-image: url(img/star2.png); }
代码引用:
<Star star={4.5} />
本文链接:http://so.lmcjl.com/news/881/