您好,欢迎访问一九零五行业门户网

react怎么实现五星评价

react实现五星评价的方法:1、设置五个元素,根据评分给不同的样式,实现代码如“starnum:['star0','star0','star0','star0','star0']...”;2、设置两个元素,根据评分设置子元素的宽度来遮挡父元素的背景图,实现代码如“ let num=(math.round(this.props.star)/2)...”。
本教程操作环境:windows10系统、react18.0.0版、dell g3电脑。
react怎么实现五星评价?
封装react组件:显示五星评价
两种简单的方式根据类似3.7和7.8这种评分显示五星评价
封装成react组件,使用时直接引用即可
第一种思想:设置五个元素,根据评分给不同的样式;第二种思想:设置两个元素,父元素给没颜色的五角星,子元素给有颜色的五角星,根据评分设置子元素的宽度来遮挡父元素的背景图
方法一:根据不同的评分设置不同的css样式
三张背景图:star0.png,star1.png,star2.png
1)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);}
2)组件js代码:
import react,{component} from 'react'class star extends component{    constructor(props){        super(props);        this.state={            starnum:['star0','star0','star0','star0','star0'] //设置默认背景图        }    }    componentdidmount(){        this.getstar(math.round(this.props.star)/2+1); //将传过来的类似7.3数字进行四舍五入再除2,得到的是类似2,3.5,6这种值    }    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;
3)在其他组件中调用star组件并传参:
<star star={4} />     页面显示为:
<star star={7.3} />    页面显示为:
这种方法需要少量的计算。
方法二:利用子元素的宽度将父元素进行遮挡
父元素背景图为无色五角星,子元素背景图为有色五角星
背景图:
css代码:
.newstar ul{    background-image: url(component/img/ico.png);}.newstar ul li{    height: 60px;    background: url(component/img/ico.png) left -62px;}
组件js代码:
import react,{component} from 'react'class star extends component{    render(){        let num=(math.round(this.props.star)/2)*20+'%'; //根据评分计算子元素的宽度        return (<div classname="newstar">            <ul>                <li style={{width:num}}></li>            </ul>        </div>)    }}export default star;
3)调用并传参
<star star={4} />     页面显示为:
<star star={7.3} />    页面显示为:
这种方式需要父和子元素的背景图大小完全一样,并且要精确计算五角星个数对应的子元素宽度
推荐学习:《react视频教程》
以上就是react怎么实现五星评价的详细内容。
其它类似信息

推荐信息