代码之家  ›  专栏  ›  技术社区  ›  Kyle Laster

如何在组件类上调用setTimeOut

  •  0
  • Kyle Laster  · 技术社区  · 6 年前

    调用setTimeOut(问题3000)后,我收到错误“不能将类作为函数调用”。“问题”需要是一个类,以便获得类接收的生命周期方法。

    到目前为止,我找到的唯一答案是在类中包含“extends React.Component”,我已经找到了。

    import React from 'react';
    import Question from './Question';
    
    setTimeout(Question, 3000);
    
    
    function Congratulations(props) {
        return(
            <div>
            <h1>Congraulations you are the champion.</h1>
            <h2>Your Score: {props.score}</h2>
        </div>
        )
    }  
    export default Congratulations;
    

    下面是组件类的前几行问题。

    export default class Question extends React.Component {
    constructor(props) {
        super(props);
    

    我希望问题在3秒钟后出现在DOM上。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Fernando Colom    6 年前

    在构造函数方法中,创建一个show=false的状态。

    setTimeOut(() => this.setState({ show: true}), 3000)
    

    在“渲染方法”中,可以使用该状态进行渲染

    {
     show &&
      // render what you want
    }
    
        2
  •  0
  •   R Esmond    6 年前

    超时不是您的问题,您只是没有反应设置代码。退房 React-Dom's render method. 您需要将设置代码包装到函数中,然后使用 setTimeout . 如果您直接调用React函数组件,那么即使是React函数组件也不会有多大作用,比如