首页 > 解决方案 > 为组件上的隐藏属性设置动画的最佳方法

问题描述

我在一个主题演讲中看到,在即将发布的 React 版本中,使用 property 隐藏组件或元素是明智之举hidden。但是,我想知道如何在切换元素的可见性时为过渡添加效果。

这里有一个小例子。如果您删除该hidden属性,则会发生转换。

class App extends React.Component {
  state = {
    isHidden: true
  }
  
  toggle = () => {
    this.setState({
      isHidden: !this.state.isHidden
    });
  }
  
  render() {
    const className = this.state.isHidden ?
      'is-hidden' : 'is-visible';
    return (
      <div>
        <button onClick={this.toggle}>toggle</button>
        <div className={'elm ' + className} hidden={this.state.isHidden}>
          Hello world
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
.elm {
  transition: opacity .5s ease;
}

.is-visible {
  opacity: 1;
}

.is-hidden {
  opacity: 0;
}
<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>

如何使用该hidden属性并仍然使用 CSS 过渡?

标签: javascriptcssreactjscss-transitions

解决方案


I don't know for sure, but I assume that the React property isHidden is doing a CSS display:none; behind the scenes. You can't transition the display property in CSS.

So if the transition is important, I'd hide the elements with CSS opacity:0 on load then add the visible class when you're ready.


推荐阅读