Javascript 反应淡入元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41852818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React fade in element
提问by GluePear
I have a Basketcomponent which needs to toggle a BasketContentscomponent when clicked on. This works:
我有一个Basket组件,BasketContents单击时需要切换组件。这有效:
constructor() {
super();
this.state = {
open: false
}
this.handleDropDown = this.handleDropDown.bind(this);
}
handleDropDown() {
this.setState({ open: !this.state.open })
}
render() {
return(
<div className="basket">
<button className="basketBtn" onClick={this.handleDropDown}>
Open
</button>
{
this.state.open
?
<BasketContents />
: null
}
</div>
)
}
It uses a conditional to either display the BasketContentscomponent or not. I now want it to fade in. I tried adding a ComponentDidMounthook to BasketContentsto transition the opacity but that doesn't work. Is there a simple way to do this?
它使用条件来显示BasketContents或不显示组件。我现在希望它淡入。我尝试添加一个ComponentDidMount钩子BasketContents来转换不透明度,但这不起作用。有没有一种简单的方法可以做到这一点?
回答by Giladd
An example using css class toggling + opacity transitions:
https://jsfiddle.net/e7zwhcbt/2/
使用 css 类切换 + 不透明度转换的示例:https:
//jsfiddle.net/e7zwhcbt/2/
Here's the interesting CSS:
这是有趣的 CSS:
.basket {
transition: opacity 0.5s;
opacity: 1;
}
.basket.hide {
opacity: 0;
pointer-events:none;
}
And the render function:
和渲染功能:
render() {
const classes = this.state.open ? 'basket' : 'basket hide'
return(
<div className="basket">
<button className="basketBtn" onClick={this.handleDropDown}>
{this.state.open ? 'Close' : 'Open'}
</button>
<BasketContents className={classes}/>
</div>
)
}
回答by Michal Cumpl
I would use react-motion like this:
我会像这样使用反应运动:
<Motion style={{currentOpacity: spring(this.state.open ? 1 : 0, { stiffness: 140, damping: 20 })}}>
{({currentOpacity}) =>
<div style={{opacity: currentOpacity}}>
<BasketContents />
</div>
}
</Motion>
I haven't tested it, but it should work.
我还没有测试过,但它应该可以工作。
回答by NewbieAid
I used react-animate-on-scrollpersonally. major props (pun intended) to its creator @dbramwell on github. Sorted my criteria in about 5 minutes. BOOM.
我react-animate-on-scroll个人用过。主要道具(双关语)给它的创建者 @dbramwell 在 github 上。在大约 5 分钟内对我的标准进行排序。繁荣。

