老师为什么我每次点击list中的任意一项时,总是表现出列表中的最后一项的删除动画呢?

来源:4-14 使用 react-transition-group 的使用(2)

ZZD271X

2021-03-22

import React, { Component, Fragment } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import './AppStyle.css';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: []
        }
        this.handleClick = this.handleClick.bind(this);
    }

    render() {
        return (
            <Fragment>
                <button onClick={this.handleClick}>
                    切换
                </button>
                <TransitionGroup>
                    {
                        this.state.list.map((item, index) => {
                            return <CSSTransition
                                timeout={1000}
                                classNames='fade'
                                unmountOnExit
                                onEntered={(el) => { el.style.color = 'blue' }}
                                appear={true}
                                key={index}
                            >
                                <div onClick={this.handleDelete.bind(this, index)}>{item}</div>
                            </CSSTransition>
                        })
                    }
                </TransitionGroup>
            </Fragment>
        )
    }
    handleClick() {
        let length=this.state.list.length;
        let list = [...this.state.list, `hello--${length}`]
        this.setState(() => {
            return {
                list
            }
        })
    }
    handleDelete(index) {
        this.setState((prevState) => {
            let list = [...prevState.list];
            list.splice(index, 1)
            return {
                list
            }
        })
    }
}

export default App
.fade-enter,.fade-appear {
    opacity:0;
}
.fade-enter-active,.fade-appear-active {
    opacity:1;
    transition:all 2s ease 0s;
}
.fade-enter-done {
    opacity:1;
}
.fade-exit {
    opacity:1;
}
.fade-exit-active {
    opacity:0;
    transition:all 4s ease 0s;
}
.fade-exit-done {
    opacity:0;
}
写回答

1回答

Dell

2021-03-23

你打印下index,看下每次删除index 是多少

0
2
Dell
回复
ZZD271X
这个很诡异,同学你把代码打个包,加我微信dell-js,我看看
2021-03-23
共2条回复

React零基础入门到实战,完成企业级项目简书网站开发

主流新技术 React-redux,React-router4,贯穿基础语法

5275 学习 · 2496 问题

查看课程