javascript - 为组件上的隐藏属性设置动画的最佳方法
问题描述
我在一个主题演讲中看到,在即将发布的 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 过渡?
解决方案
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.
推荐阅读
- three.js - 是否可以在 THREE.Object3D 上应用旋转/缩放/位置
- pandas-groupby - 如何计算一周中每天的平均人数?
- scala - 从数据集的行中选择一列
- r - 如何将 sapply 代码转换为 vapply 代码
- pytorch - Pytorch model.train() 和 model.eval() 行为怪异
- c# - dotnet build 间歇性退出,并在 linux 上出现分段错误(核心转储)或 139
- javascript - 如何在每 20 秒显示 5 秒后关闭此元素
- python - 不要为我的 GAN 实现获得完整的 GPU 利用率
- python - 正确语法的 Mysql 8.0 语法错误检查手册
- ios - 自定义 URL 方案错误:此应用不允许查询方案