programing

react.js 컴포넌트를 클릭해서 애니메이션의 끝을 검출하려면 어떻게 해야 합니까?

fastcode 2023. 3. 16. 21:56
반응형

react.js 컴포넌트를 클릭해서 애니메이션의 끝을 검출하려면 어떻게 해야 합니까?

사용자가 DOM 요소를 클릭했을 때 반응 컴포넌트가 뒤집히도록 하고 싶다.애니메이션 믹스인에 대한 문서가 있지만 "Enter" 및 "leave" 이벤트용으로 설정되어 있는 것 같습니다.사용자 입력에 따라 애니메이션이 시작되고 완료되면 알림을 받는 가장 좋은 방법은 무엇입니까?현재 리스트 아이템을 가지고 있는데 삭제, 편집, 저장 등의 버튼을 몇 개만 넘기면 됩니다.아마 내가 서류에서 뭔가 놓친 것 같아.

애니메이션 믹스인

http://facebook.github.io/react/docs/animation.html

클릭 후 상태 업데이트, 클래스 추가 및 녹음할 수 있습니다.animationend이벤트입니다.

class ClickMe extends React.Component {
  constructor(props) {
    super(props)
    this.state = { fade: false }
  }
  render() {
    const fade = this.state.fade

    return (
      <button
        ref='button'
        onClick={() => this.setState({ fade: true })}
        onAnimationEnd={() => this.setState({ fade: false })}
        className={fade ? 'fade' : ''}>
        Click me!
      </button>
    )
  }
}

plnkr:https://next.plnkr.co/edit/gbt0W4SQhnZILlmQ?open=Hello.js&deferRun=1&preview 를 참조해 주세요.

편집: 애니메이션 종료 이벤트를 지원하는 현재 React를 반영하도록 업데이트되었습니다.

React는 애니메이션 이벤트를 포함하는 합성 이벤트를 사용합니다.매뉴얼은 https://reactjs.org/docs/events.html#animation-events 에서 찾을 수 있습니다.아래 승인된 답변을 업데이트했습니다.

class ClickMe extends React.Component {
  state = {fade: false};

  render () {
    const {fade} = this.state;

    return (
      <button
        onClick={() => this.setState({fade: true})}
        onAnimationEnd={() => this.setState({fade: false})}
        className={fade ? 'fade' : ''}>
          Click me!
      </button>
    )
  }
}

Hooks 및 prevState를 사용하여 이벤트핸들러 내부의 상태를 갱신하지 않는 방법

 import { useState } from 'react'

export default function Animation() {
  const [fade, setFade] = useState(false)
  
  const triggerFade = () => {
    setFade(prevState => {
      return !prevState
    })
  }
  
  return (
    <div
      onAnimationEnd={triggerFade}
      className={fade ? 'fadedClass' : 'visibleClass'}
    >
      Watch me fade
    </div>
    <button onClick={triggerFade}>Click Me</button>
  )
}

다음은 JQueries, 기타 libs, 등록 또는 sms 없이 순수 Reactjs 이벤트를 사용한 답변입니다.

핵심은 애니메이션 키프레임 이름을 기능 매개 변수로 제공하는 것입니다.

CSS

.Modal {
    position: fixed;
    top: 30%;
    left: 25%;
    transition: all 0.3s ease-out;
}
.ModalOpen {
    animation: openModal 0.4s ease-out forwards;
}
.ModalClosed {
    animation: closeModal 0.4s ease-out forwards;
}

@keyframes openModal {
    0% { transform: translateY(-100%); }
    100% { transform: translateY(0);   }
}

@keyframes closeModal {
    0% { transform: translateY(0); }
    100% { transform: translateY(-100%);}
}

JS

const modal = ({ 
  isShown, isMounted, 
  initiateUnmountAction, unmountAction
}) => {
  const cssClasses = [
    "Modal",
    props.isShown ? "ModalOpen" : "ModalClosed"
  ];
  return (
    <Fragment>
      {isMounted && <div className={cssClasses.join(' ')}
        onAnimationEnd={event => 
          {event.animationName == "closeModal" && unmountAction}
      }>
        <h1>A Modal</h1>
        <button className="Button" onClick={initiateUnmountAction}>
          Dismiss
      </button>
      </div>}
    </Fragment>

  );
};

가장 인기 있고 사용하기 쉬운 패키지:

https://www.npmjs.com/package/react-transition-group

인스톨:

npm install react-transition-group

사용방법:

import { CSSTransition } from 'react-transition-group';

<CSSTransition
  in={toShow} // boolean value passed via state/props to either mount or unmount this component
  timeout={300}
  classNames='my-element' // IMP!
  unmountOnExit
>
  <ComponentToBeAnimated />
</CSSTransition>

메모: CSS의 클래스 속성을 사용하여 다음 스타일을 적용하십시오.

.my-element-enter {
  opacity: 0;
  transform: scale(0.9);
}
.my-element-enter-active {
  opacity: 1;
  transform: translateX(0);
  transition: opacity 300ms, transform 300ms;
}
.my-element-exit {
  opacity: 1;
}
.my-element-exit-active {
  opacity: 0;
  transform: scale(0.9);
  transition: opacity 300ms, transform 300ms;
}

사용한 적이 없다React단,CSS3 animations/transitions다음과 같은 작업을 수행할 수 있습니다.

 element.addEventListener( 'webkitTransitionEnd', function( event ) { 

   console.log( 'Complete');

 }, false );

저는 이 프로젝트를 리액트 해머 통합 프로젝트에서 성공적으로 사용했습니다.해머 이벤트와 리액트 애니메이션의 예가 몇 가지 있습니다.

CSS를 사용하여 실행할 수도 있습니다.

IfTailwindCSS를 사용하고 있습니다.정답은, 「아래의 클래스 추가」입니다.

hover:opacity-90 focus:opacity-100

else미가공 css

.class-name:hover{
    opacity: 0.9;
}
.class-name:focus{
    opacity: 1;
}

그런 식으로 깨달았어요. 그게 도움이 됐으면 좋겠어요.

CSS:

.mainStyle {
  /*some-styles*/
  height: 250px;
  background-color: red;
}

.openAnimation {
  animation: open-menu .4s linear forwards;
}

.closeAnimation {
  animation: close-menu .4s linear forwards;
}

@keyframes open-menu {
  0% {width: 0;} /*You can use animation what do You need*/
  100% {width: 80%;}
}

@keyframes close-menu {
  0% {width: 80%;}
  100% {width: 0;}
}

JSX 파일

Import React, { useState } from React;

const AnimatedMenu = () => {
  const [isOpen, setOpen] = useState(false);

  const animationEndHandler = ({ animationName }) => {
    if (animationName === 'open-menu') {
        setOpen(true);
    }

    if (animationName === 'close-menu') {
        setOpen(false);
    }
  };

  return (
    <>
      <div 
        onAnimationEnd={(event) => animationEndHandler(event)}
        className={isOpen ? 'mainStyles open' : 'mainStyles close'}
      >
        hide/show
      </div>
      <button onClick={() => setOpen(!isOpen)}>click me</button>
    </>
  );
};

언급URL : https://stackoverflow.com/questions/24111813/how-can-i-animate-a-react-js-component-onclick-and-detect-the-end-of-the-animati

반응형