[英]How to set Time delay to after calling function?
I have a function that randomly changes the background of a page in react.我有一个 function 随机改变页面背景的反应。 But I want the background color to FADE to the next random color so I tried below.但我希望背景颜色淡化为下一个随机颜色,所以我在下面尝试。
class App extends Component {
constructor(props) {
super(props);
this.state = {
quotes: [],
selectedQuoteIndex: null,
background: 'green'
}
changeBackground() {
let background = "#" + ((1<<24)*Math.random() | 0).toString(16);
this.setState({background});
}, 2000;
assignNewQuoteIndex() {
this.setState({ selectedQuoteIndex: this.generateNewQuoteIndex() });
}
backgroundQuoteChange(){
this.assignNewQuoteIndex();
this.changeBackground();
}
render() {
return (
<div style={{
width: '100vw',
height: '100vh',
backgroundColor: this.state.background
}}>
<Button id="new-quote"
size={'small'}
onClick={backgroundQuoteChange}>Next Color & Quote
</Button>
)
I use this function on a button which has onClick.我在具有 onClick 的按钮上使用此 function。 Not working:/不工作:/
Just set a transition on the respective div with 1s delay and ease-in-out timing function.只需在相应的 div 上设置一个具有 1 秒延迟和缓入出时序 function 的转换。
transition: background-color ease-in-out 1s;
Here's a sandbox: https://codesandbox.io/s/elegant-franklin-d6z99这是一个沙盒: https://codesandbox.io/s/elegant-franklin-d6z99
I'd highly suggest getting your basics of HTML, CSS and JS stronger before jumping into a framework.在进入框架之前,我强烈建议您先掌握 HTML、CSS 和 JS 的基础知识。 You definitely need some work there.你肯定需要在那里做一些工作。
You can simply use css transtion您可以简单地使用 css 转换
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quotes: [],
selectedQuoteIndex: null,
background: "green"
};
}
changeBackground = () => {
let background = "#" + (((1 << 24) * Math.random()) | 0).toString(16);
this.setState({ background });
};
render() {
return (
<>
<div
style={{
width: "100vw",
height: "100vh",
transition: "background-color 1s",
backgroundColor: this.state.background
}}
/>
<button type="button" onClick={this.changeBackground}>
Next Color & quote
</button>
</>
);
}
}
Here is a the example on stackblitz这是stackblitz上的一个例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.