对那些花时间和精力回答我之前的问题的人表示歉意。我最初以为我不会得到帮助,所以我自己开始研究它。我走得很远,所以我不想从头开始重建我所做的一切。
此反应成分是一排星星。当用户单击一个星星时,它和所有以前的星星将从空变为满。如果单击星号2,则星号1和2都变满,依此类推。此ALMOST起作用。这是我的代码:
import React, { Component } from "react";
class Starset0 extends Component {
rate = event => {
const {id} = event.target;
console.log("You clicked: " + id);
var i;
for (i = 1; i < parseFloat(id) + 1; i++) {
console.log("I should change the following: " + i);
document.getElementById(i).setAttribute("src", "{require('./full-star.png')}");
//okay, so you've...kinda got it working...kind of
}
};
render() {
return (
<div id = "rating0">
<img onClick = {this.rate} class = "star" id = "1" src = {require('./empty-star.png')} />
<img onClick = {this.rate} class = "star" id = "2" src = {require('./empty-star.png')} />
<img onClick = {this.rate} class = "star" id = "3" src = {require('./empty-star.png')} />
<img onClick = {this.rate} class = "star" id = "4" src = {require('./empty-star.png')}/>
<img onClick = {this.rate} class = "star" id = "5" src = {require('./empty-star.png')}/>
</div>
);
}
}
export default Starset0;
问题在于,不是恒星变满,而是它们只是停止渲染。它们将替换为该图像未找到的图标。为什么是这样?如果我手动替换source属性,它将显示完整的星号。
答案 0 :(得分:0)
尝试更改此
"{require('./full-star.png')}"
到
{require('./full-star.png')}
"{require('./full-star.png')}" is executed as string. so its not fetching the image.
答案 1 :(得分:0)
外部化require语句并将其用作变量。
尝试一下
import React, { Component } from "react";
class Starset0 extends Component {
const fullStarSrc = require('./full-star.png');
const emptyStarSrc = require('./empty-star.png');
rate = event => {
const { id } = event.target;
console.log("You clicked: " + id);
var i;
for (i = 1; i <= 5; i++) {
if(i <= parseInt(id)) {
console.log("I should change the following: " + i);
document.getElementById(i).setAttribute("src",
fullStarSrc);
}
else {
console.log("I should change the following: " + i);
document.getElementById(i).setAttribute("src",
emptyStarSrc);
}
//okay, so you've...kinda got it working...kind of
}
};
render() {
return (
<div id="rating0">
<img onClick={this.rate} class="star" id="1" src=
{emptyStarSrc} />
<img onClick={this.rate} class="star" id="2" src=
{emptyStarSrc} />
<img onClick={this.rate} class="star" id="3" src=
{emptyStarSrc} />
<img onClick={this.rate} class="star" id="4" src=
{emptyStarSrc} />
<img onClick={this.rate} class="star" id="5" src=
{this.emptyStarSrc} />
</div>
);
}
}
export default Starset0;