3

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

我的组件代码:

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;
}

它不做任何高度动画!

4

1 回答 1

1

我得到了相关答案的帮助。

将每个 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;
}
于 2018-06-25T16:12:59.063 回答