简体   繁体   中英

How to set Time delay to after calling function?

I have a function that randomly changes the background of a page in react. 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. Not working:/

Just set a transition on the respective div with 1s delay and ease-in-out timing function.

transition: background-color ease-in-out 1s;

Here's a sandbox: 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. You definitely need some work there.

You can simply use css transtion

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM