gpt4 book ai didi

javascript - 是否可以在 react 中向有条件显示的组件添加任何动画?

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:33 26 4
gpt4 key购买 nike

我想制作一个行为类似于引导面板的 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;

是否可以为这个元素的扩展添加一些过渡?如有必要,可以更改逻辑。

最佳答案

您可以使用 @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>

关于javascript - 是否可以在 react 中向有条件显示的组件添加任何动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50600625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com