setState
方法的第二个参数是可选的回调函数。因此,一旦你将this.state.show
设置为true
,你可以使用这个回调参数来递增opacity
。回调函数可能如下所示:
fadingIn(){
const timer = setInterval(() => {
if (this.state.opacity === 1) {
clearInterval(timer);
}
this.setState({ opacity: this.state.opacity + 0.1 })
}, 100);
}
所以,由于您已经添加了componentDidMount
,您可以在那里触发它。
componentDidMount(){
setTimeout(() => this.setState({ show: true }, this.fadingIn), 1000)
}
render(){
return <div>
{!this.state.show
? <div>Regular</div>
: <div style={{opacity: this.state.opacity}}>Fade In</div>}
</div>
}
示例演示
更新
尝试类似这样的内容:
const withFading = ({ Faded, duration, isOut }) => {
const inEffect = `
@keyframes react-fade-in {
0% { opacity: 0; }
50% { opacity: 0; }
100% { opacity: 1; }
}
`;
const outEffect = `
@keyframes react-fade-out {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 0; }
}
`;
return (
<div>
// Here we add style tag with the css for fadeIn & fadeOut
// depends on a input value of isOut parameter.
// It does same thing as an example from below
// <style>
// body { your css rules }
// </style>
// with react we can pass `body { ... }` as a child into
// style tag as i did.
<style children={isOut ? outEffect : inEffect} />
<div style={{
animationDuration: `${duration}s`,
animationIterationCount: 1,
animationName: `react-fade-${(isOut ? 'out' : 'in')}`,
animationTimingFunction: isOut ? 'ease-out' : 'ease-in'
}}
><Faded /></div>
</div>
)
}
const Hello = () => <div>Hello</div>
const FadedHello = withFading({ Faded: Hello, duration: 2, isOut: false});
操作示例