是否可以在反应中向有条件显示的组件添加任何动画?
Posted
技术标签:
【中文标题】是否可以在反应中向有条件显示的组件添加任何动画?【英文标题】:Is it possible to add any animation to conditionally displayed component in react? 【发布时间】:2018-11-09 01:39:55 【问题描述】:我想制作一个类似于引导面板的 div(单击时扩展并显示其他信息)。我想出了以下解决方案:
import React from 'react';
import './Test.css'
import './Collapsible'
import Collapsible from './Collapsible';
class Test extends React.Component
constructor()
super()
this.state =
isHidden: true
CollapseClickHandler()
const temp = !this.state.isHidden
this.setState( isHidden : temp )
render()
return (
<div className="hero" onClick=this.CollapseClickHandler.bind(this)>
<ul className="collapse">
<li>Name: John Doe</li>
<li>Year of birth: 1751</li>
<li>Height: 123</li>
<li>Mass: 124</li>
<li>
Home: Cardboard box
</li>
</ul>
this.state.isHidden ? null : <Collapsible />
</div>
)
export default Test;
是否可以在此元素的扩展中添加一些过渡?如有必要,可以更改逻辑。
【问题讨论】:
【参考方案1】:您可以使用 @keyframes
规则 CSS 动画来完成此操作
class App extends React.Component
constructor(props)
super(props)
this.state =
show: true,fadeOut: true ;
toggle = () =>
this.setState( fadeOut: !this.state.fadeOut )
if(this.state.show === false)
setTimeout(() =>
this.setState( show: !this.state.show )
, 1000)
else
this.setState( show: !this.state.show )
render()
return (
<div>
<button onClick=this.toggle>Click</button>
this.state.show ? null : <div className=this.state.fadeOut ? 'fadeOut' : 'fade'><Child /></div>
</div>
);
class Child extends React.Component
render()
return (
<div className="fade">
<h1>Fade In/Out Using CSS </h1>
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
.fade
animation: fadein 2s;
-moz-animation: fadein 2s; /* Firefox */
-webkit-animation: fadein 2s; /* Safari and Chrome */
-o-animation: fadein 2s; /* Opera */
.fadeOut
animation: fadeout 2s;
-moz-animation: fadeout 2s; /* Firefox */
-webkit-animation: fadeout 2s; /* Safari and Chrome */
-o-animation: fadeout 2s; /* Opera */
@keyframes fadein
from
opacity:0;
to
opacity:1;
@-moz-keyframes fadein /* Firefox */
from
opacity:0;
to
opacity:1;
@-webkit-keyframes fadein /* Safari and Chrome */
from
opacity:0;
to
opacity:1;
@-o-keyframes fadein /* Opera */
from
opacity:0;
to
opacity: 1;
@keyframes fadeout
from
opacity:1;
to
opacity: 0;
@-moz-keyframes fadeout /* Firefox */
from
opacity:1;
to
opacity: 0;
@-webkit-keyframes fadeout /* Safari and Chrome */
from
opacity:1;
to
opacity:0;
@-o-keyframes fadeout /* Opera */
from
opacity:1;
to
opacity: 0;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
【讨论】:
以上是关于是否可以在反应中向有条件显示的组件添加任何动画?的主要内容,如果未能解决你的问题,请参考以下文章