gpt4 book ai didi

javascript - 使用循环更改组件特征(样式)

转载 作者:行者123 更新时间:2023-12-02 23:32:55 30 4
gpt4 key购买 nike

是否有办法使用无限循环来遍历每个组件(例如:按钮/标签)特征?在我的应用程序中,我在特定屏幕上有 24 个按钮,我想一直一一更改每个按钮的颜色。我想一直一一改变每个按钮的颜色。我都尝试过 componentdidmountcomponentwillmount ,但它会发生一次。当我转到另一个屏幕并返回时,循环不会开始。 enter image description here

最佳答案

如果您想定期执行此操作,您可以跟踪您所在州的所选项目,例如:

// 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>

关于javascript - 使用循环更改组件特征(样式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413860/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com