在 React 中动画显示/隐藏 table 行

Animate the show / hide of table rows in React

看过ReactTransitionGroup的例子。在这些示例中,我们正在对待办事项列表的新行和已删除的 table 行进行动画处理。示例中显示的动画是淡入淡出动画。如何展开/缩小 table 行而不是淡入淡出动画?

我的组件代码:

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

class App extends Component {
  state = { name: '', names: [] };

  handleNameChange(e) {
    this.setState({ name: e.target.value });
  }

  handleSubmit() {
    let { names } = this.state;
    names = names.slice();
    names.push(this.state.name);
    this.setState({ names });
  }

  handleDelete(index) {
    let { names } = this.state;
    names = names.slice();
    names.splice(index, 1);
    this.setState({ names });
  }

  render() {
    return (
      <div className="app">
        <input type="text" placeholder="Enter name" value={this.state.name} onChange={this.handleNameChange.bind(this)} />
        <button onClick={this.handleSubmit.bind(this)}>Submit</button>
        <table border="1" style={{ marginTop: 20 }}>
          <thead>
            <tr>
              <th width="300">Name</th>
              <th width="100">Delete</th>
            </tr>
          </thead>
          <TransitionGroup component="tbody">
            {this.state.names.map((name, index) => (
              <CSSTransition
                key={index}
                timeout={5000}
                classNames="fade"
              >
                <tr>
                  <td>{name}</td>
                  <td>
                    <button onClick={this.handleDelete.bind(this, index)}>Delete</button>
                  </td>
                </tr>
              </CSSTransition>
            ))}
          </TransitionGroup>
        </table>
      </div>
    );
  }
}

export default App;

我的CSS:

.fade-enter {
  max-height: 0;
}

.fade-enter-active {
  max-height: 40px;
  transition: all 5000ms ease-in;
}
.fade-exit {
  max-height: 40px;
}
.fade-exit-active {
  max-height: 0;
  transition: all 5000ms ease-in;
}

它不做任何高度动画!

我得到了related answer的帮助。

将每个 td 内容包装在 div 内。

<TransitionGroup component="tbody">
  {this.state.names.map((name, index) => (
    <CSSTransition
      key={index}
      timeout={500}
      classNames="fade"
    >
      <tr>
        <td><div>{name}</div></td>
        <td>
          <div><button onClick={this.handleDelete.bind(this, index)}>Delete</button></div>
        </td>
      </tr>
    </CSSTransition>
  ))}
</TransitionGroup>

使用 CSS 过渡 类 设置 div 的样式。

.fade-enter div {
  overflow-y: hidden;
  max-height: 0;
}

.fade-enter-active div {
  max-height: 50px;
  transition: all 500ms ease-in;
}
.fade-exit div {
  max-height: 50px;
}
.fade-exit-active div {
  max-height: 0;
  overflow-y: hidden;
  transition: all 500ms ease-in;
}