在componentDidMount

时间:2018-07-31 09:35:49

标签: javascript css reactjs

我正在尝试使用react和CSS创建过渡。我想向span添加一个类来创建动画-请参见下面的示例。

有人知道问题出在CSS还是我的JavaScript。

class App extends React.Component {
  state = {
    class: null
  };

  componentDidMount() {
    this.setState({
      class: "active"
    });
  }

  render() {
    return (
      <div className="progress-bar-container">
        <span
          className={this.state.class ? 
                     "progress-bar" : 
                     `${this.state.class} progress-bar`}
        />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
.progress-bar-container {
  border: 0;
  height: 4px;
  position: relative;
  background: red;
}

.progress-bar {
  -webkit-transition: width 2s; /* Safari */
  transition: width 5s;
  width: 0%;
}

.progress-bar.active {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

2 个答案:

答案 0 :(得分:3)

您可以使用其他方法,并将OUT: C:\File1.csv SELECT * FROM table1; OUT: C:\File2.csv SELECT * FROM table2; OUT: C:\File3.csv SELECT * FROM table3; 类附加到active方法中。

setTimeout
class App extends React.Component {
  state = {
    class: null
  };

  componentDidMount() {
    setTimeout(() => this.refs.progressBar.classList.add("active"), 100)
  }

  render() {
    return ( 
      <div className = "progress-bar-container" >
        <span className="progress-bar" ref="progressBar"/>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render( < App / > , rootElement);
.progress-bar-container {
  border: 0;
  height: 4px;
  position: relative;
  background: red;
}

.progress-bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: green;
  transition: width 5s;
  width: 0px;
}

.progress-bar.active {
  width: 100%;
}

答案 1 :(得分:0)

您可以使用requestAnimationFrame()触发挂载的过渡。我认为这样做比依赖setTimeout()更为可靠。

componentDidMount() {
    requestAnimationFrame(() => {
        this.setState({
            class: "active"
        });
    });
}

来源:https://www.pluralsight.com/guides/handling-componentdidmount-issue-css-transition