


index.wxml
<input type="number" bindinput="onScoreInput" placeholder="输入成绩(0-6)" />
<button bindtap="onSubmit">提交</button>
<!-- 第一种方法:输入0-6的数字,点击提交按钮来高亮展示星星 -->
<star-rating id="star-rating" current-score="{{currentScore}}"></star-rating>
<!-- 第二种方法:输入0-6的数字自动高亮展示星星 -->
<star-rating id="star-rating" score="{{currentScore}}"></star-rating>
<!-- 第三种方法 -->
<!--
<input type="number" bindinput="onScoreChange" placeholder="输入成绩(0-6)" />
<star-rating score="{{currentScore}}"></star-rating>
index.js设置:
Page({
data: {
currentScore: 0
},
onScoreChange: function(newScore) {
this.setData({ currentScore: newScore });
}
});
-->
index.json
{
"usingComponents": {
"star-rating":"/components/star13/index"
}
}
index.js
// const StarRating = require('../../../components/star13/index');
Page({
data: {
currentScore: 0
},
onScoreInput: function (e) {
const score = parseInt(e.detail.value);
this.setData({
currentScore: score
});
},
onSubmit: function () {
this.selectComponent('#star-rating').updateStars(this.data.currentScore);
}
});
新建组件文件:
/components/star13/index.wxml
<view class="star-rating">
<block wx:for="{{stars}}" wx:key="index">
<image src="{{item.type === 'filled' ? '/images/stars_select.png' : '/images/stars_unselect.png'}}" mode="aspectFit" class="star"></image>
</block>
</view>
/components/star13/index.js
Component({
properties: {
score: {
type: Number,
value: 0,
observer: function(newVal) {
this.updateStars(newVal);
}
}
},
data: {
totalStars: 6,
stars: []
},
attached: function() {
const initialStars = Array.from({ length: this.data.totalStars }, () => ({
type: 'gray'
}));
this.setData({ stars: initialStars });
},
methods: {
updateStars: function(newScore) {
if (newScore < 0 || newScore > this.data.totalStars) {
console.error('成绩超出范围');
return;
}
const updatedStars = this.data.stars.map((star, index) => ({
type: index < newScore ? 'filled' : 'gray'
}));
this.setData({ stars: updatedStars });
}
}
});
/components/star13/index.wxss
.star-rating{
display:inline;
}
.star-rating image{
width:40px;
height:40px;
display:inline-block;
}