问题
I have a Basket
component which needs to toggle a BasketContents
component when clicked on. This works:
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 BasketContents
component or not. I now want it to fade in. I tried adding a ComponentDidMount
hook to BasketContents
to transition the opacity but that doesn't work. Is there a simple way to do this?
回答1:
An example using css class toggling + opacity transitions:
https://jsfiddle.net/e7zwhcbt/2/
Here's the interesting 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>
)
}
回答2:
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.
回答3:
I used react-animate-on-scroll
personally. major props (pun intended) to its creator @dbramwell on github. Sorted my criteria in about 5 minutes. BOOM. 🎉
来源:https://stackoverflow.com/questions/41852818/react-fade-in-element