繁体   English   中英

调用 function 后如何设置延时?

[英]How to set Time delay to after calling function?

我有一个 function 随机改变页面背景的反应。 但我希望背景颜色淡化为下一个随机颜色,所以我在下面尝试。

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

我在具有 onClick 的按钮上使用此 function。 不工作:/

只需在相应的 div 上设置一个具有 1 秒延迟和缓入出时序 function 的转换。

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

这是一个沙盒: https://codesandbox.io/s/elegant-franklin-d6z99

在进入框架之前,我强烈建议您先掌握 HTML、CSS 和 JS 的基础知识。 你肯定需要在那里做一些工作。

您可以简单地使用 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>
     </>
   );
  }
}

这是stackblitz上的一个例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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