这个简单的东西应该很容易实现,但是我把头发拉出来是多么复杂。
我想要做的就是动画安装和卸载React组件,就是这样。这是我到目前为止所尝试的以及为什么每个解决方案都不起作用:
ReactCSSTransitionGroup
- 我根本不使用CSS类,它是所有JS样式,所以这不起作用。ReactTransitionGroup
- 这个较低级别的API很棒,但它要求你在动画完成时使用回调,所以只使用CSS过渡在这里不起作用。总有动画库,这导致下一点:TransitionMotion
非常混乱,而且过于复杂,我需要的东西。left: -10000px
),但我宁愿不去那条路线。我认为它很hacky,我希望卸载我的组件,以便清理它们并且不会使DOM混乱。我想要一些易于实现的东西。在mount上,动画一组样式;在卸载时,为相同(或另一组)样式设置动画。完成。它还必须在多个平台上具有高性能。
我在这里碰到了一堵砖墙。如果我遗漏了一些东西并且有一个简单的方法可以做到这一点,请告诉我。
这有点长,但我已经使用了所有本机事件和方法来实现这个动画。没有ReactCSSTransitionGroup
,ReactTransitionGroup
等。
我用过的东西
onTransitionEnd
事件这是如何工作的
mounted
)和默认样式(opacity: 0
)挂载元素componentDidMount
(componentWillReceiveProps
进行进一步更新)以超时(使其异步)更改样式(opacity: 1
)。opacity: 0
),onTransitionEnd
,从DOM中删除元素。继续循环。
仔细阅读代码,你就明白了。如果需要澄清,请发表评论。
希望这可以帮助。
class App extends React.Component{
constructor(props) {
super(props)
this.transitionEnd = this.transitionEnd.bind(this)
this.mountStyle = this.mountStyle.bind(this)
this.unMountStyle = this.unMountStyle.bind(this)
this.state ={ //base css
show: true,
style :{
fontSize: 60,
opacity: 0,
transition: 'all 2s ease',
}
}
}
componentWillReceiveProps(newProps) { // check for the mounted props
if(!newProps.mounted)
return this.unMountStyle() // call outro animation when mounted prop is false
this.setState({ // remount the node when the mounted prop is true
show: true
})
setTimeout(this.mountStyle, 10) // call the into animation
}
unMountStyle() { // css for unmount animation
this.setState({
style: {
fontSize: 60,
opacity: 0,
transition: 'all 1s ease',
}
})
}
mountStyle() { // css for mount animation
this.setState({
style: {
fontSize: 60,
opacity: 1,
transition: 'all 1s ease',
}
})
}
componentDidMount(){
setTimeout(this.mountStyle, 10) // call the into animation
}
transitionEnd(){
if(!this.props.mounted){ // remove the node on transition end when the mounted prop is false
this.setState({
show: false
})
}
}
render() {
return this.state.show && <h1 style={this.state.style} onTransitionEnd={this.transitionEnd}>Hello</h1>
}
}
class Parent extends React.Component{
constructor(props){
super(props)
this.buttonClick = this.buttonClick.bind(this)
this.state = {
showChild: true,
}
}
buttonClick(){
this.setState({
showChild: !this.state.showChild
})
}
render(){
return <div>
<App onTransitionEnd={this.transitionEnd} mounted={this.state.showChild}/>
<button onClick={this.buttonClick}>{this.state.showChild ? 'Unmount': 'Mount'}</button>
</div>
}
}
ReactDOM.render(<Parent />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
我也迫切需要单组件动画。我厌倦了使用React Motion,但我正在为这样一个微不足道的问题拉扯我的头发..(我的事)。经过一些谷歌搜索,我发现他们的git回购这篇文章。希望它可以帮助某人..
Referenced From & also the credit。这对我来说现在很有用。我的用例是在加载和卸载的情况下动画和卸载的模态。
class Example extends React.Component {
constructor() {
super();
this.toggle = this.toggle.bind(this);
this.onRest = this.onRest.bind(this);
this.state = {
open: true,
animating: false,
};
}
toggle() {
this.setState({
open: !this.state.open,
animating: true,
});
}
onRest() {
this.setState({ animating: false });
}
render() {
const { open, animating } = this.state;
return (
<div>
<button onClick={this.toggle}>
Toggle
</button>
{(open || animating) && (
<Motion
defaultStyle={open ? { opacity: 0 } : { opacity: 1 }}
style={open ? { opacity: spring(1) } : { opacity: spring(0) }}
onRest={this.onRest}
>
{(style => (
<div className="box" style={style} />
))}
</Motion>
)}
</div>
);
}
}
利用从Pranesh的答案中获得的知识,我想出了一个可配置和可重用的替代解决方案:
const AnimatedMount = ({ unmountedStyle, mountedStyle }) => {
return (Wrapped) => class extends Component {
constructor(props) {
super(props);
this.state = {
style: unmountedStyle,
};
}
componentWillEnter(callback) {
this.onTransitionEnd = callback;
setTimeout(() => {
this.setState({
style: mountedStyle,
});
}, 20);
}
componentWillLeave(callback) {
this.onTransitionEnd = callback;
this.setState({
style: unmountedStyle,
});
}
render() {
return <div
style={this.state.style}
onTransitionEnd={this.onTransitionEnd}
>
<Wrapped { ...this.props } />
</div>
}
}
};
用法:
import React, { PureComponent } from 'react';
class Thing extends PureComponent {
render() {
return <div>
Test!
</div>
}
}
export default AnimatedMount({
unmountedStyle: {
opacity: 0,
transform: 'translate3d(-100px, 0, 0)',
transition: 'opacity 250ms ease-out, transform 250ms ease-out',
},
mountedStyle: {
opacity: 1,
transform: 'translate3d(0, 0, 0)',
transition: 'opacity 1.5s ease-out, transform 1.5s ease-out',
},
})(Thing);
最后,在另一个组件的render
方法中:
return <div>
<ReactTransitionGroup>
<Thing />
</ReactTransitionGroup>
</div>
我在工作期间反驳了这个问题,看起来很简单,它实际上并不在React中。在正常情况下,您可以呈现如下内容:
this.state.show ? {childen} : null;
随着this.state.show
的变化,孩子们立即安装/卸载。
我采取的一种方法是创建一个包装器组件Animate
并使用它
<Animate show={this.state.show}>
{childen}
</Animate>
现在随着this.state.show
的变化,我们可以用getDerivedStateFromProps(componentWillReceiveProps)
感知道具变化并创建中间渲染阶段来执行动画。
我们从安装或卸载儿童时开始使用静态舞台。
一旦我们检测到show
标志变化,我们进入准备阶段,我们从height
计算必要的属性,如width
和ReactDOM.findDOMNode.getBoundingClientRect()
。
然后输入Animate State我们可以使用css过渡将高度,宽度和不透明度从0更改为计算值(如果卸载则更改为0)。
在过渡结束时,我们使用onTransitionEnd
api改回Static
阶段。
关于阶段如何顺利转移的更多细节,但这可能是整体想法:)
如果有兴趣,我创建了一个React库https://github.com/MingruiZhang/react-animate-mount来分享我的解决方案。任何反馈欢迎:)
这是我的解决方案,使用新的钩子API(使用TypeScript),based on this post,用于延迟组件的卸载阶段:
function useDelayUnmount(isMounted: boolean, delayTime: number) {
const [ shouldRender, setShouldRender ] = useState(false);
useEffect(() => {
let timeoutId: NodeJS.Timeout;
if (isMounted && !shouldRender) {
setShouldRender(true);
}
else if(!isMounted && shouldRender) {
timeoutId = setTimeout(
() => setShouldRender(false),
delayTime
);
}
return () => clearTimeout(timeoutId);
});
return shouldRender;
}
用法:
const Parent: React.FC = () => {
const [ isMounted, setIsMounted ] = useState(true);
const shouldRenderChild = useDelayUnmount(isMounted, 500);
const mountedStyle = {opacity: 1, transition: "opacity 500ms ease-in"};
const unmountedStyle = {opacity: 0, transition: "opacity 500ms ease-in"};
const handleToggleClicked = () => {
setIsMounted(!isMounted);
}
return (
<>
{shouldRenderChild &&
<Child style={isMounted ? mountedStyle : unmountedStyle} />}
<button onClick={handleToggleClicked}>Click me!</button>
</>
);
}
CodeSandbox链接。
我认为使用Transition
的react-transition-group
可能是跟踪安装/卸载的最简单方法。它非常灵活。我正在使用一些类来展示它是多么容易使用,但你绝对可以使用addEndListener
prop来连接你自己的JS动画 - 我使用GSAP也有很多运气。
沙箱:https://codesandbox.io/s/k9xl9mkx2o
这是我的代码。
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Transition } from "react-transition-group";
import styled from "styled-components";
const H1 = styled.h1`
transition: 0.2s;
/* Hidden init state */
opacity: 0;
transform: translateY(-10px);
&.enter,
&.entered {
/* Animate in state */
opacity: 1;
transform: translateY(0px);
}
&.exit,
&.exited {
/* Animate out state */
opacity: 0;
transform: translateY(-10px);
}
`;
const App = () => {
const [show, changeShow] = useState(false);
const onClick = () => {
changeShow(prev => {
return !prev;
});
};
return (
<div>
<button onClick={onClick}>{show ? "Hide" : "Show"}</button>
<Transition mountOnEnter unmountOnExit timeout={200} in={show}>
{state => {
let className = state;
return <H1 className={className}>Animate me</H1>;
}}
</Transition>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
对于那些考虑反应运动的人来说,在安装和卸载时为单个组件制作动画可能会让人难以置信。
有一个名为react-motion-ui-pack的库,使这个过程更容易开始。它是react-motion的包装器,这意味着您可以从库中获得所有好处(即,您可以中断动画,同时进行多次卸载)。
用法:
import Transition from 'react-motion-ui-pack'
<Transition
enter={{ opacity: 1, translateX: 0 }}
leave={{ opacity: 0, translateX: -100 }}
component={false}
>
{ this.state.show &&
<div key="hello">
Hello
</div>
}
</Transition>
Enter定义组件的最终状态应该是什么; leave是卸载组件时应用的样式。
您可能会发现,一旦您使用了UI包几次,react-motion库可能就不再那么令人生畏了。
使用react-move可以更轻松地设置进入和退出过渡的动画。
在这里我的2cents:感谢@deckele的解决方案。我的解决方案基于他的,它是有状态的组件版本,完全可重用。
在这里我的沙箱:https://codesandbox.io/s/302mkm1m。
在这里我的snippet.js:
import ReactDOM from "react-dom";
import React, { Component } from "react";
import style from "./styles.css";
class Tooltip extends Component {
state = {
shouldRender: false,
isMounted: true,
}
shouldComponentUpdate(nextProps, nextState) {
if (this.state.shouldRender !== nextState.shouldRender) {
return true
}
else if (this.state.isMounted !== nextState.isMounted) {
console.log("ismounted!")
return true
}
return false
}
displayTooltip = () => {
var timeoutId;
if (this.state.isMounted && !this.state.shouldRender) {
this.setState({ shouldRender: true });
} else if (!this.state.isMounted && this.state.shouldRender) {
timeoutId = setTimeout(() => this.setState({ shouldRender: false }), 500);
() => clearTimeout(timeoutId)
}
return;
}
mountedStyle = { animation: "inAnimation 500ms ease-in" };
unmountedStyle = { animation: "outAnimation 510ms ease-in" };
handleToggleClicked = () => {
console.log("in handleToggleClicked")
this.setState((currentState) => ({
isMounted: !currentState.isMounted
}), this.displayTooltip());
};
render() {
var { children } = this.props
return (
<main>
{this.state.shouldRender && (
<div className={style.tooltip_wrapper} >
<h1 style={!(this.state.isMounted) ? this.mountedStyle : this.unmountedStyle}>{children}</h1>
</div>
)}
<style>{`
@keyframes inAnimation {
0% {
transform: scale(0.1);
opacity: 0;
}
60% {
transform: scale(1.2);
opacity: 1;
}
100% {
transform: scale(1);
}
}
@keyframes outAnimation {
20% {
transform: scale(1.2);
}
100% {
transform: scale(0);
opacity: 0;
}
}
`}
</style>
</main>
);
}
}
class App extends Component{
render(){
return (
<div className="App">
<button onClick={() => this.refs.tooltipWrapper.handleToggleClicked()}>
click here </button>
<Tooltip
ref="tooltipWrapper"
>
Here a children
</Tooltip>
</div>
)};
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这是我在2019年解决这个问题的方法,同时制作了一个加载微调器。我正在使用React功能组件。
我有一个父App组件,它有一个子Spinner组件。
应用程序具有应用程序是否正在加载的状态。加载应用程序时,Spinner正常呈现。当应用程序未加载时(isLoading
为false)Spinner将使用prop shouldUnmount
进行渲染。
App.js:
import React, {useState} from 'react';
import Spinner from './Spinner';
const App = function() {
const [isLoading, setIsLoading] = useState(false);
return (
<div className='App'>
{isLoading ? <Spinner /> : <Spinner shouldUnmount />}
</div>
);
};
export default App;
Spinner有关于它是否隐藏的状态。在开始时,使用默认道具和状态,Spinner正常呈现。 Spinner-fadeIn
类动画它渐渐消失。当Spinner收到道具shouldUnmount
时,它会用Spinner-fadeOut
类渲染,动画渐渐消失。
但是我也想让组件在淡出后卸载。
此时我尝试使用onAnimationEnd
React合成事件,类似于上面@ pranesh-ravi的解决方案,但它没有用。相反,我使用setTimeout
将状态设置为隐藏,延迟与动画的长度相同。 Spinner将在延迟后使用isHidden === true
更新,并且不会呈现任何内容。
这里的关键是父母不会卸载孩子,它告诉孩子什么时候卸载,孩子在处理卸载业务后卸下自己。
Spinner.js:
import React, {useState} from 'react';
import './Spinner.css';
const Spinner = function(props) {
const [isHidden, setIsHidden] = useState(false);
if(isHidden) {
return null
} else if(props.shouldUnmount) {
setTimeout(setIsHidden, 500, true);
return (
<div className='Spinner Spinner-fadeOut' />
);
} else {
return (
<div className='Spinner Spinner-fadeIn' />
);
}
};
export default Spinner;
Spinner.css:
.Spinner {
position: fixed;
display: block;
z-index: 999;
top: 50%;
left: 50%;
margin: -40px 0 0 -20px;
height: 40px;
width: 40px;
border: 5px solid #00000080;
border-left-color: #bbbbbbbb;
border-radius: 40px;
}
.Spinner-fadeIn {
animation:
rotate 1s linear infinite,
fadeIn .5s linear forwards;
}
.Spinner-fadeOut {
animation:
rotate 1s linear infinite,
fadeOut .5s linear forwards;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes rotate {
100% {
transform: rotate(360deg);
}
}