【发布时间】:2021-02-05 18:18:33
【问题描述】:
所以我有一个标题,它每 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>
【问题讨论】:
标签: javascript html reactjs radio-button state