所以我有一个标题,它每5秒循环显示4张图像。用户还可以使用5个单选按钮自己循环浏览这些图像。
活动/选中单选按钮的样式在用户单击时应用,但是,如果计时器切换图像,则活动单选按钮保持不变。
我知道这是基于以下代码的预期行为,我只是想知道如何更改选中的单选按钮以匹配其当前图像!
任何帮助将不胜感激!
constructor(props) {
super(props);
this.state = {
time: 0,
start: 0,
currentIndex: 0
};
this.setIndex = this.setIndex.bind(this);
this.startTimer = this.startTimer.bind(this);
this.resetTimer = this.resetTimer.bind(this);
}
componentDidMount() {
this.startTimer();
}
componentDidUpdate() {
if (this.state.time === 5) {
this.setIndex(this.state.currentIndex + 1);
}
}
startTimer() {
this.timer = setInterval(
() =>
this.setState({
time: this.state.time + 1
}),
1000
);
}
resetTimer() {
this.setState({ time: 0 });
}
setIndex(index, e) {
console.log("changing");
if (index < 0) {
index = headers.length - 1;
}
if (index >= headers.length) {
index = 0;
}
this.setState({
currentIndex: index,
time: Date.now() - this.state.start
});
this.resetTimer();
}
... 跳过代码
<div className="carousel">
<img
alt="carousel-header"
className="background-img"
src={headers[this.state.currentIndex].image}
/>
<div className="buttons-container">
<input
type="radio"
value="1"
defaultChecked
name="index"
onClick={() => this.setIndex(0)}
></input>
<input
type="radio"
value="2"
name="index"
onClick={() => this.setIndex(1)}
></input>
<input
type="radio"
value="3"
name="index"
onClick={() => this.setIndex(2)}
></input>
<input
type="radio"
value="4"
name="index"
onClick={() => this.setIndex(3)}
></input>
</div>
</div>
答案 0 :(得分:0)
您可以检查currentIndex
中的自动更改单选按钮。
在render
函数中
const { currentIndex } = this.state
<div className="buttons-container">
<input
type="radio"
value="1"
defaultChecked
name="index"
checked={currentIndex === 0}
onClick={() => this.setIndex(0)}
></input>
<input
type="radio"
value="2"
name="index"
checked={currentIndex === 1}
onClick={() => this.setIndex(1)}
></input>
<input
type="radio"
value="3"
name="index"
checked={currentIndex === 2}
onClick={() => this.setIndex(2)}
></input>
<input
type="radio"
value="4"
name="index"
checked={currentIndex === 3}
onClick={() => this.setIndex(3)}
></input>
</div>
答案 1 :(得分:0)
如果我的理解正确,您正在使用单选按钮,这些单选按钮会在点击时被激活(这是默认的HTML行为),而在使用计时器时则不会。
这只是小菜一碟,每次计时器切换背景时,您只需通过JS激活它们即可。
您可能认为setIndex()函数将在每次计时器进行更改时运行,但事实并非如此,因为该函数仅在人们实际单击收音机或发出onClick事件时启动。 由于:
onClick={() => this.setIndex(3)}
要解决此问题,您应该修改以下代码:
startTimer() {
this.timer = setInterval(
() =>
this.setState({
time: this.state.time + 1
}),
1000
);
}
resetTimer() {
this.setState({ time: 0 });
}
您应该在其中设置单选框的值,并更新索引状态。
重置时,请记住重置状态值功能并将单选框的值设置为#1收音机。