css - 一段时间后向 React 组件添加类

标签 css reactjs

我有一个 react 组件:

React.createComponent({

  render: function () {

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

  }
});

渲染后几秒钟,我希望它从组件内添加一个类。该类的目的是通过动画显示组件。我不认为它是真正的状态更改,因为除了为组件提供动画介绍之外,它对应用程序没有任何影响,因此我讨厌通过更改 store/从组件外部启动它状态。

简单来说我该如何做到这一点?像这样的东西:

{setTimeout(function () {

  this.addClass('show'); //pseudo code

}, 1000)}

显然我可以使用 jQuery,但这感觉是反 React 的,并且容易产生副作用。

最佳答案

I don't regard it as a real change of state, as it has no affect on the application other than to give the component an animated introduction

更改组件中的状态似乎是这种情况下自然且正确的解决方案。组件状态的更改会触发重新渲染,这正是您所需要的。考虑一下我们在这里讨论的是组件的状态,而不是应用程序的状态。

在 React 中,你不直接处理 DOM(例如通过使用 jQuery),相反你的组件状态应该“驱动”渲染的内容,所以你让 React 对状态/属性的变化做出“ react ”并更新 DOM让您反射(reflect)当前状态:

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 中使用 setTimeout 时,你需要小心并确保在组件卸载时取消超时,否则如果超时仍处于挂起状态并且你的组件,你的超时回调函数无论如何都会运行被删除。

如果您需要执行初始安装动画或更复杂的动画,请考虑使用 ReactCssTransitionGroup,它可以为您处理超时和其他开箱即用的事情:https://facebook.github.io/react/docs/animation.html

关于css - 一段时间后向 React 组件添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40806073/

相关文章:

javascript - 可以在鼠标左键单击时触发 context.js 上下文菜单

html - Chrome 51 中的背景大小转换 - 错误还是功能?

css - 如何显示特色图片?

javascript - 如何使用 JavaScript 设置带前缀的 CSS3 过渡效果?

javascript - 使用 create-react-app 我得到 EEXIST : file already exists

html - 在包装 div 内平铺 div,而不是让它们出现在外面

javascript - 在 ref 属性中使用字符串文字已被弃用

javascript - 使用 SVG 矩形单击处理程序更改 react 状态

javascript - 如何在material-ui中将日期对象转换为字符串? ReactJS。在表格上显示日期

javascript - 如何在 Mobx 中执行可观察函数?