
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} />
上面是“reactjs如何做一个五星评价功能”的全面内容,想了解更多关于 reactjs 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_2984.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

js删除对象中指定参数(数组中指定参数)
Game Worlds:通过简单的文本描述或上传图像,快速生成游戏中的角色及场景
在线小工具集合【帮小忙】之温度转换工具
css3+js如何做一个动态点赞效果