In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how to achieve a Transition transition animation component for React. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
I. basic realization
We are implementing the basic over-animation components, and we need to achieve simple animation effects by switching CSS styles.
First, let's install the classnames plug-in:
Npm install classnames-save-dev
And classnaems is a simple JavaScript utility for conditionally connecting classnames together. So let's create a new Transition folder in the component directory and a new Transition.jsx file in the folder, as follows:
Import React from 'react'import classnames from' classnames'/** * css transition animation component * * @ visibleName Transition transition animation * / class Transition extends React.Component {render () {const {children} = this.props const transition = ({children}) return transition}} export default Transition
In the file we define the attribute definition name by using a small hump; and we use the JSX syntax in the file, let's take a look at the following example code:
Const name = 'Josh Perez';const element = Hello, {name}
This code is equivalent to this string of code:
Const element = Hello, Josh Perez
Of course, we should be careful when using the JSX syntax, because the JSX syntax is closer to JavaScript than html, so in React DOM we use a small hump for naming instead of the html attribute name convention.
In addition, the props.children in React contains all the child nodes of the component, that is, the content between the start and end tags of the component, as shown in the following example:
Default button
Get the props.children in the Button component, and you get the string "default button".
So let's create a new index.js under the Transition folder and export the Transition component, as shown in the following code:
Import Transition from'. / Transition.jsx'export {Transition} export default Transition
When you are finished, add the props check and set the action default value for the component in the Transition.jsx file, as follows:
Import PropTypes from 'prop-types'const propTypes = {/ * * execute animation * / action: PropTypes.bool, / * * class name of switched css animation * / toggleClass: PropTypes.string} const defaultProps = {action: false}
At this point, we use prop-ty.pes to implement runtime type checking. However, it is important to note that prop-ty.pes is a runtime; type checking tool, let's take a look at the complete Transition component code as follows:
Import React from 'react'import PropTypes from' prop-types'import classnames from 'classnames'const propTypes = {/ * * perform animation * / action: PropTypes.bool / * * class name of switched css animation * / toggleClass: PropTypes.string} const defaultProps = {action: false} / * css transition animation component * * @ visibleName Transition transition animation * / class Transition extends React.Component {static propTypes = propTypes static defaultProps = defaultProps render () {const {className, action, toggleClass Children} = this.props const transition = ({children}) return transition}} export default Transition
The CSS code is as follows:
.fade {transition: opacity 0.15s linear;} .fade: not (.show) {opacity: 0;}
The JS code is as follows:
Import React from 'react';import Transition from'. / Transition';class Anime extends React.Component {constructor (props) {super (props) this.state = {action: true}} render () {const btnText = this.state.action? 'fade out': 'fade in' return (fade out this.setState ({action:! this.state.action})} > {btnText})}}
In this way, we only need to use the Anime component where we need to use animation.
Second, achieve Animate.css compatibility
We all know that Animate.css is a powerful library of preset CSS3 animation. Since we usually use these two opposite class styles when entering and leaving the animation, we need to add two attributes, enterClass and leaveClass, to our Transition component to switch the animation, as shown below:
Import React from 'react'import PropTypes from' prop-types'import classnames from 'classnames'const propTypes = {/ * * execute animation * / action: PropTypes.bool, / * * class name of the switched css animation * / toggleClass: PropTypes.string, / * * enter the class name of the animation, invalid * / enterClass: PropTypes.string, / * * leave the class name of the animation Invalid * / leaveClass: PropTypes.string} const defaultProps = {action: false} / * * css transition animation component * * @ visibleName Transition transition animation * / class Transition extends React.Component {static propTypes = propTypes static defaultProps = defaultProps render () {const {className, action, toggleClass, enterClass, leaveClass Children} = this.props return ({children})}} export default Transition
Of course, we should also note that because toggleClass is suitable for situations where you enter the animation and switch to the same class style as you leave the animation, and enterClass and leaveClass use those situations where you enter and leave the animation to switch between different class styles, they and toggleClass cannot coexist.
Then we will try the Transition component after adding Animate.css. The code is as follows:
Import React from 'react';import' animate.css';class Anime extends React.Component {constructor (props) {super (props) this.state = {action: true}} render () {return (pop-up this.setState ({action:! this.state.action})} > {this.state.action? 'Pop up': 'pop in')}}
III. Function expansion
After the implementation of the above method, we know that the Transition component can be applied in many scenarios, but the function is not very rich, so we need to extend the interface of Transition. First, let's add the props attribute and set the default value, as shown in the following code:
Const propTypes = {..., / * * delayed animation execution time * / delay: PropTypes.string, / * * animation execution time * / duration: PropTypes.string, / * * number of animation execution times It is only valid when performing CSS3 animation * / count: PropTypes.number, / * animation ease function * / easing: PropTypes.oneOf (['linear',' ease', 'ease-in',' ease-out', 'ease-in-out']), / * * whether to force reverse playback of animation in turn, invalid when count is 1 * / reverse: PropTypes.bool} const defaultProps = {count: 1, reverse: false}
According to the style set by props, the code is as follows:
/ / Animation style const styleText = () = > {let style = {} / / set delay if (delay) {style.transitionDelay = delay style.animationDelay = delay} / / set playback duration if (duration) {style.transitionDuration = duration style.animationDuration = duration} / / set playback times if (count) {style.animationIterationCount = count} / / set delay letter Number if (easing) {style.transitionTimingFunction = easing style.animationTimingFunction = easing} / / set the animation direction if (reverse) {style.animationDirection = 'alternate'} return style}) ()
The complete code is as follows:
Import React from 'react'import PropTypes from' prop-types'import classnames from 'classnames'const propTypes = {/ * * execute animation * / action: PropTypes.bool, / * * class name of the switched css animation * / toggleClass: PropTypes.string, / * * enter the class name of the animation, invalid * / enterClass: PropTypes.string, / * * leave the class name of the animation Invalid * / leaveClass: PropTypes.string, / * * delayed animation execution time * / delay: PropTypes.string, / * * animation execution time * / duration: PropTypes.string, / * * animation execution times Valid only when performing CSS3 animation * / count: PropTypes.number, / * Animation ease function * / easing: PropTypes.oneOf (['linear',' ease', 'ease-in',' ease-out', 'ease-in-out']), / * * whether to force the animation to be played in reverse in turn Invalid * / reverse: PropTypes.bool} const defaultProps = {action: false, count: 1, reverse: false} / * css transition animation component * * @ visibleName Transition transition animation * / class Transition extends React.Component {static propTypes = propTypes static defaultProps = defaultProps render () {const {className, action, toggleClass, enterClass, leaveClass, delay, duration, count, easing Reverse Children} = this.props / / Animation style const styleText = () = > {let style = {} / / set delay if (delay) {style.transitionDelay = delay style.animationDelay = delay} / / set playback duration if (duration) {style.transitionDuration = duration style.animationDuration = duration } / / set playback times if (count) {style.animationIterationCount = count} / / set ease function if (easing) {style.transitionTimingFunction = easing style.animationTimingFunction = easing} / / set if (reverse) {style.animationDirection = 'alternate'} return style }) () return ({children})}} export default Transition
Here let's take a look at the related added attributes of Transition:
Delay: specifies the delay before the animation starts.
Duration: specifies the time, in seconds or milliseconds, to complete the animation.
Count: specifies the number of times the animation should be played.
Easing: specifies the speed curve of the animation.
Reverse: specifies whether the animation should be played in reverse in turn.
IV. Optimization
Then let's optimize Transition. We mainly focus on animation monitoring, uninstalling components and other related compatibility issues. So we add the props attribute to the code and set the default value. The code is as follows:
Const propTypes = {..., / * * callback at the end of the animation * / onEnd: PropTypes.func, / * * unload the element at the end of the animation * / exist: PropTypes.bool} const defaultProps = {..., reverse: false, exist: false}
Next, the event code for the end of the animation monitoring:
/ * * css transition animation component * * @ visibleName Transition transition animation * / class Transition extends React.Component {. OnEnd = e = > {const {onEnd, action Exist} = this.props if (onEnd) {onEnd (e)} / / Uninstall the DOM element if (! action & & exist) {const node = e.target [XSS _ clean] node [XSS _ clean] .removeChild (node)}} / * handlers for onEnd callbacks to the end of animation event * * @ param {string} type-event unbinding type: add-bind event Remove-remove event binding * / handleEndListener (type = 'add') {const el = ReactDOM.findDOMNode (this) .querySelector (' .transition-wrapper') const events = ['animationend',' transitionend'] events.forEach (ev = > {el [`${type} EventListener`] (ev, this.onEnd, false)} componentDidMount () {this.handleEndListener ()} componentWillUnmount () {const {action) Exist} = this.props if (! action & & exist) {this.handleEndListener ('remove')}} render () {...}}
In the code, we can see that two life cycle functions, componentDidMount and componentWillUnmount, are used.
React-dom also provides us with DOM methods that can be used in React applications. By getting compatibility animationend and transitionend events. The code to verify the function method is as follows:
/ * * browser compatible event detection function * * @ param {node} el-DOM element that triggers events * @ param {array} events-possible event types * @ returns {*} * / const whichEvent = (el, events) = > {const len = events.length for (var I = 0; I)
< len; i++) { if (el.style[i]) { return events[i]; } }} 修改 handleEndListener 函数代码如下所示: /** * css过渡动画组件 * * @visibleName Transition 过渡动画 */class Transition extends React.Component { ... /** * 对动画结束事件 onEnd 回调的处理函数 * * @param {string} type - 事件解绑定类型: add - 绑定事件,remove - 移除事件绑定 */ handleEndListener (type = 'add') { const el = ReactDOM.findDOMNode(this).querySelector('.transition-wrapper') const events = ['AnimationEnd', 'TransitionEnd'] events.forEach(ev =>{const eventType = whichEvent (el, [ev.toLowerCase (), `webkit$ {ev} `]) el [` ${type} EventListener`] (eventType, this.onEnd, false)}.}
After that, we have completed the development of the entire Transition component, and the relevant complete code is as follows:
Import React from 'react'import PropTypes from' prop-types'import classnames from 'classnames'import ReactDOM from' react-dom'const propTypes = {/ * * execute animation * / action: PropTypes.bool, / * * class name of the switched css animation * / toggleClass: PropTypes.string, / * * enter the class name of the animation, invalid * / enterClass: PropTypes.string, / * * leave the animation class name when toggleClass exists Invalid * / leaveClass: PropTypes.string, / * * delayed animation execution time * / delay: PropTypes.string, / * * animation execution time * / duration: PropTypes.string, / * * animation execution times Valid only when performing CSS3 animation * / count: PropTypes.number, / * Animation ease function * / easing: PropTypes.oneOf (['linear',' ease', 'ease-in',' ease-out', 'ease-in-out']), / * * whether to force the animation to be played in reverse in turn Invalid when count is 1 * / reverse: PropTypes.bool, / * * callback at the end of animation * / onEnd: PropTypes.func, / * * unload elements at the end of animation * / exist: PropTypes.bool} const defaultProps = {action: false, count: 1, reverse: false Exist: false} / * * browser compatible event detection function * * @ param {node} el-DOM element * @ param {array} events-possible event types * @ returns {*} * / const whichEvent = (el, events) = > {const len = events.length for (var I = 0) I
< len; i++) { if (el.style[i]) { return events[i]; } }}/** * css过渡动画组件 * * @visibleName Transition 过渡动画 */class Transition extends React.Component { static propTypes = propTypes static defaultProps = defaultProps onEnd = e =>{const {onEnd, action Exist} = this.props if (onEnd) {onEnd (e)} / / Uninstall the DOM element if (! action & & exist) {const node = e.target [XSS _ clean] node [XSS _ clean] .removeChild (node)}} / * handlers for onEnd callbacks to the end of animation event * * @ param {string} type-event unbinding type: add-bind event Remove-remove event binding * / handleEndListener (type = 'add') {const el = ReactDOM.findDOMNode (this) .querySelector (' .transition-wrapper') const events = ['AnimationEnd',' TransitionEnd'] events.forEach (ev = > {const eventType = whichEvent (el, [ev.toLowerCase (), `webkit$ {ev} `]) el [` ${type} EventListener`] (eventType, this.onEnd) False)} componentDidMount () {this.handleEndListener ()} componentWillUnmount () {const {action, exist} = this.props if (! action & & exist) {this.handleEndListener ('remove')}} render () {const {className, action, toggleClass, enterClass, leaveClass, delay, duration, count, easing, reverse Children} = this.props / / Animation style const styleText = () = > {let style = {} / / set delay if (delay) {style.transitionDelay = delay style.animationDelay = delay} / / set playback duration if (duration) {style.transitionDuration = duration style.animationDuration = duration } / / set playback times if (count) {style.animationIterationCount = count} / / set ease function if (easing) {style.transitionTimingFunction = easing style.animationTimingFunction = easing} / / set if (reverse) {style.animationDirection = 'alternate'} return style }) () const transition = ({children}) return transition}} export default Transition's article on "how React implements a Transition transition animation component" ends here. Hope that the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.