Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Css 在一定时间后将类添加到React组件_Css_Reactjs - Fatal编程技术网

Css 在一定时间后将类添加到React组件

Css 在一定时间后将类添加到React组件,css,reactjs,Css,Reactjs,我有一个反应组件: React.createComponent({ render: function () { return (<div className="some-component"></div>); } }); 很明显,我可以使用jQuery,但这会让人感觉反作用,而且容易产生副作用 我不认为这是一个真正的状态变化,因为它对应用程序没有影响,除了给组件一个动画的介绍 组件状态的改变似乎是这种情况下的自然和适当的解决方案。组件状态的更改会触

我有一个反应组件:

React.createComponent({

  render: function () {

    return (<div className="some-component"></div>);

  }
});
很明显,我可以使用jQuery,但这会让人感觉反作用,而且容易产生副作用

我不认为这是一个真正的状态变化,因为它对应用程序没有影响,除了给组件一个动画的介绍

组件状态的改变似乎是这种情况下的自然和适当的解决方案。组件状态的更改会触发重新渲染,这正是此处需要的。考虑一下我们讨论的是组件的状态,而不是你的应用程序。 在React中,您不直接处理DOM(例如,通过使用jQuery),相反,您的组件状态应该“驱动”呈现的内容,因此您可以让React对状态/道具的更改做出“反应”,并更新DOM以反映当前状态:

React.createComponent({

  componentDidMount () {
    this.timeoutId = setTimeout(function () {
        this.setState({show: true});
    }.bind(this), 1000);
  } 

  componentWillUnmount () {
    if (this.timeoutId) {
        clearTimeout(this.timeoutId);
    }
  }

  render: function () {

    return (<div className={this.state.show ? 'show' : null}></div>);

  }
});
React.createComponent({
组件安装(){
this.timeoutId=setTimeout(函数(){
this.setState({show:true});
}.绑定(本),1000);
} 
组件将卸载(){
if(this.timeoutId){
clearTimeout(this.timeoutId);
}
}
渲染:函数(){
返回();
}
});
在React中使用
setTimeout
时,您需要小心,并确保在卸载组件时取消超时,否则,如果超时仍处于挂起状态且组件已被删除,则超时回调函数仍将运行


如果需要执行初始安装动画或更复杂的动画,请考虑使用<代码> ReCTCsStRANSISTION组< /代码>,它可以直接为您处理超时和其他事情:

难道您不能在生命周期方法componentDidMount中使用setTimeout,只使用组件级别的状态来定义您的组件上的类名吗?如果组件是“dumb”(只是一个带有
render
方法的函数)?@vsync我想您的意思是“如果它是一个功能组件(即,只是一个函数),那该怎么办呢?”我认为对于这种情况,您需要一个类,因为您需要生命周期挂钩来正确初始化和清除超时。或者,您可以将超时逻辑移到父组件(类)中并将当前时间作为道具传递给子功能组件。或者查看useState和useEffect以使用本地状态和生命周期挂钩。
React.createComponent({

  componentDidMount () {
    this.timeoutId = setTimeout(function () {
        this.setState({show: true});
    }.bind(this), 1000);
  } 

  componentWillUnmount () {
    if (this.timeoutId) {
        clearTimeout(this.timeoutId);
    }
  }

  render: function () {

    return (<div className={this.state.show ? 'show' : null}></div>);

  }
});