React Transition Group v1 重渲染时过渡动画不生效问题排查
Hey there! Let's get that transition animation working properly for your quiz app. The root problem here is how React Transition Group v1 detects content changes to trigger animations—right now, it doesn't realize when a new question is loaded.
The Core Issue
CSSTransitionGroup relies on unique key props to identify when elements are added or removed. In your current Form component, you're wrapping multiple elements (<h3> and <RadioGroup>) directly inside the transition group without a single container with a unique key. When the question changes, React just updates the content of existing elements instead of unmounting the old content and mounting the new content—so no transition fires.
Step-by-Step Fix
Here's how to adjust your Form component to trigger the transition correctly:
- Wrap all the question content (heading + radio buttons) in a single
<div> - Give this div a unique
keytied to the current question (so it changes every time the question updates) - Double-check your prop types to include the
questionprop (it was missing before!)
Modified Form component code:
import React from 'react'; import PropTypes from 'prop-types'; import { RadioGroup, RadioButton } from 'react-radio-buttons'; import { CSSTransitionGroup } from 'react-transition-group'; function Form (props) { return ( <div> <CSSTransitionGroup transitionName='slide' transitionEnterTimeout={300} transitionLeaveTimeout={300} > {/* Unique key triggers the transition when question changes */} <div key={props.question}> <h3>{props.question}</h3> <RadioGroup onChange={props.onSelect}> { props.answers.map(answer => <RadioButton key={answer.answer} value={answer.archetype}> {answer.answer} </RadioButton> ) } </RadioGroup> </div> </CSSTransitionGroup> </div> ) } Form.propTypes = { answers: PropTypes.array.isRequired, onSelect: PropTypes.func.isRequired, question: PropTypes.string.isRequired // Add this missing prop type }; export default Form;
Quick Side Note
I noticed your Panel component is exported as PanelOne but imported as Panel in App.js—make sure these names match (either rename the component to Panel or update the import to import PanelOne from './components/Panel'; and use <PanelOne> in the render method) to avoid any unexpected errors.
With these changes, when you select an answer and the question updates, the old question content will fade out, and the new one will fade in exactly as you expected!
内容的提问来源于stack exchange,提问作者bkula

