首页 > 解决方案 > react-transition-group CSSTransition,以null为条件

问题描述

试图让一个简单的淡入/淡出过渡工作。

我尝试将<CSSTransition>周围移动到不同的区域,但无济于事。我在另一个映射子组件的组件中成功地使用了它,但不明白为什么它在这种情况下不起作用,因为我将它与子组件一起渲染,如果子组件完全返回的话。

子组件

const Error = (props) => {
  return (
    <CSSTransition timeout={400} classNames={errorTransition}>
      <span> {props.errorString} </span>
    </CSSTransition>
  )
}

父组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { CSSTransition } from 'react-transition-group';

import type { InfoState } from './state';
import { closeError } from './actions';

const mapStateToProps = (state: {info: InfoState}) => ({
  info: state.info.data.info,
  infoError: state.info.infoError,
});

const mapDispatchToProps = dispatch => ({
  closeError: () => dispatch(closeError()),
});

class Parent extends Component<Props, State> {
  state = { info: this.props.info };

  handleChange = (e) => {
    this.setState({ info: e.target.value });
    this.props.closeError();
  }

  render() {
    if (this.props.info === null) {
      return (
        <div className="info-wrapper">
          <input
            type="text"
            value={this.state.info ? this.state.info : '' }
            onChange={this.handleChange}
          />
        </div>
        <div className="info-error">
          { this.props.infoError !== ''
            ? <Error 
                key={this.state.info} 
                errorString={this.props.infoError} 
              />
            : null
           }
        </div>
      )
    }
    return ( <div> things </div> )
  }
}

CSS

.errorTransition-enter {
  opacity: 0.01;
}
.errorTransition-enter-active {
  opacity: 1;
  transition: all 400ms ease-out;
}
.errorTransition-exit {
  opacity: 1;
}
.errorTransition-exit-active {
  opacity: 0.01;
  transition: all 400ms ease-out;
}

标签: reactjscss-transitionsreact-transition-group

解决方案


我在有条件地删除用<CSSTransition>. 为了解决这个问题,我用<CSSTransition>一个元素包裹了<TransitionGroup>元素并使用了它的childFactory 属性childFactoryprop 可以这样使用:

  <TransitionGroup
     childFactory={child => React.cloneElement(child)}
  >
    <CSSTransition timeout={400} classNames={errorTransition}>
      <span> {props.errorString} </span>
    </CSSTransition>
  </TransitionGroup>

推荐阅读