简体   繁体   English

在200毫秒后以组件样式ReactJS更改不透明度

[英]change opacity after 200ms in component style ReactJS

I using ReactJS framework and I try that, this component to change its style after 200ms from opacity 0 to opacity 1 . 我使用ReactJS框架,并尝试通过200ms将该组件的样式从opacity 0更改为opacity 1 Is it possible to do such a setTimeout? 可以执行这样的setTimeout吗?

<GreetingHeadline styles={?} id={this.props.user.id} />

Here's a working example that uses toggles between hidden/visible classes. 这是一个使用隐藏/可见类之间切换的工作示例。 I've added the transition so the effect can be more easily seen (200ms is a very short time) but you can remove it in your code. 我已经添加了过渡,因此可以更容易看到效果(200ms是非常短的时间),但是您可以在代码中将其删除。

 class Test extends React.Component { constructor() { super(); this.state = { classes: 'hidden' }; } componentDidMount() { setTimeout(() => this.setState({ classes: 'visible' }), 200); } render() { const { classes } = this.state; return <div className={classes}>Text to be rendered</div>; } } ReactDOM.render(<Test />, document.getElementById('container')); 
 .hidden { opacity: 0; } .visible { opacity: 1; transition: opacity 1s linear;} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="container"></div> 

You can put a variable to the state of the GreetingHeadline's parent component: 您可以将一个变量设置为GreetingHeadline的父组件的状态:

constructor() {
  this.state = {
    transparent: true;
  }
}

Then you can use setTimeout in the componentDidMount lifetime's method: 然后可以在componentDidMount生命周期的方法中使用setTimeout:

componentDidMount() {
  this.setTimeout(() => {
    this.setState({ transparent: false });
  }, 200);
}

Finally you can use variable from the state within your GreetingHeadline component's props: 最后,您可以在GreetingHeadline组件的props中使用状态中的变量:

<GreetingHeadline
  styles={{ opacity: this.state.transparent ? '0.7' : '1' }}
  id={this.props.user.id}
/>

Setting a class is the easiest way to change the opacity. 设置类是更改不透明度的最简单方法。 Here's an example that also uses an animation to "smooth" the transition. 这是一个使用动画“平滑”过渡的示例。

https://codesandbox.io/s/j371123nq9 https://codesandbox.io/s/j371123nq9

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

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