我通常在基于类的 comp 中只使用 componentDidMount 和 setTimeout 来设置状态并动态地添加一个类到主 div 并为其设置动画。我有点想做同样的事情,只是将类传递给 func comp,但它不起作用。我现在想坚持使用纯CSS。
我在 React 中有一个功能组件,如下所示:
import React from 'react';
export default (props.class) => {
return (
<div className={`animate ${props.class}`}>
Hello World
</div>
)
}
Main App:
import React, { Component} from 'react';
import FuncComp from './FuncComp';
export default class App extends Component {
constructor(props){
super(props)
this.state = { class: '' }
}
componentDidMount() {
setTimeout(() => { this.setState({class: 'animateAction'}), 0)
}
render(){
return (
<div>
<FuncComp class={this.state.class} />
</div>
)
}
}
外部 CSS:
.animate {
transform: scaleY(0);
transition: transform 1s ease;
}
.animateAction {
transform: scaleY(1);
}
最佳答案
我想这将是一个有点令人困惑的答案,但我找到了一种在加载时设置动画的方法以及一种延迟组件卸载的方法。
这是针对功能组件的,因为您可以在组件本身的基于类的组件中完成其中的一半。
编辑:根据我的发现,这也适用于基于类的 comp。
注意:base是基类,action是动画要发生的 Action 。
import React, { Component } from 'react'
export default Comp => {
return class extends React.Component {
constructor(props) {
super(props)
this.state = {
shouldRender: this.props.isMounted,
didMount: false
}
}
componentWillReceiveProps(nextProps) {
if (this.props.isMounted && !nextProps.isMounted) {
setTimeout(() => {
this.setState({ shouldRender: false })
}, this.props.delayTime)
this.setState({ didMount: false })
} else if (!this.props.isMounted && nextProps.isMounted) {
setTimeout(() => {
this.setState({ didMount: true })
}, 0)
this.setState({ shouldRender: true })
}
}
render() {
const { didMount } = this.state
const { base, action, isMounted } = this.props
return this.state.shouldRender ? (
<div className={`${base} ${didMount && isMounted ? action : ''}`}>
<Comp {...this.props} />
</div>
) : null
}
}
}
好的,现在使用这个新的 HOC,我们可以像这样包装我们的 func comp。
import React from 'react'
import AnimateHOC from './AnimateHOC'
const myFuncComp = (props.class) => {
return (
<h1>
Hello World
</h1>
)
}
const AnimateComp = AnimateHOC(myFuncComp);
在基于类的 comp 中使用如下:
render() {
return (
<div>
<AnimateComp
delayTime={500}
isMounted={this.state.isMounted}
base={'animate'}
action={'animateAction'}
/>
<button onClick={this.setState({ isMounted: !this.state.isMounted }) }>Toggle</button>
</div>
)
}
最后是你的外部 CSS:
.animate {
transform: scaleY(0);
transform-origin: top;
transition: all 0.5s linear;
}
.animateAction {
transform: scaleY(1);
}
CRITICAL :将延迟时间与您的动画时间相匹配,否则将无法正常工作。延迟时间以 MS 为单位,所以 500 = .5s
关于css - 如何在 react 中为 func comp 设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50875614/