是否有使用无限循环遍历每个组件(例如:按钮/标签)的特征?在我的应用程序中,我在特定屏幕上有24个按钮,我想一直不断地更改每个按钮的颜色。我想一直一次更改每个按钮的颜色。我已经尝试过componentdidmount
和componentwillmount
,但是都发生一次。当我转到另一个屏幕并返回时,循环不会开始。
答案 0 :(得分:1)
如果您希望在一定时间间隔内执行此操作,则可以跟踪状态下的所选项目,例如:
// In your constructor (since you mentioned `componentDidMount`, I know you're using classes)
this.state = {
selectedControl: 0,
// ...your other state
};
在componentDidMount
中,启动间隔计时器:
componentDidMount() {
this.timerHandle = setInterval(() => {
this.setState(({selectedControl, controls}) =>
({selectedControl: (selectedControl + 1) % controls.length})
);
}, 2000); // 2000ms = two seconds
}
呈现控件时,突出显示所选的控件:
render() {
const {selectedControl, controls} = this.state;
return (
<div>
{controls.map((control, index) => (
<input key={index} type="button" value={control} className={index === selectedControl ? "highlighted" : undefined} />
))}
</div>
);
}
请注意,在所有情况下,我都假设this.state.controls
是您的控件数组。
根据需要进行调整,只是为了使您正确地前进。
实时示例(比2秒快一点):
class Example extends React.Component {
constructor(props) {
super(props);
// In your constructor (since you mentioned `componentDidMount`, I know you're using classes)
this.state = {
selectedControl: 0,
controls: ["one", "two", "three", "four"]
};
}
componentDidMount() {
this.timerHandle = setInterval(() => {
this.setState(({selectedControl, controls}) =>
({selectedControl: (selectedControl + 1) % controls.length})
);
}, 800); // 800ms = 0.8 seconds
}
render() {
const {selectedControl, controls} = this.state;
return (
<div>
{controls.map((control, index) => (
<input key={index} type="button" value={control} className={index === selectedControl ? "highlighted" : undefined} />
))}
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById("root"));
.highlighted {
font-weight: bold;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.development.js"></script>