我通常在基于类的 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 是你想要为动画发生的动作。
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);
}
关键:将延迟时间与您的动画时间相匹配,否则将无法正常工作。延迟时间以 MS 为单位,所以 500 = .5s
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句