如何仅使用内联样式将淡入动画添加到<div>fading-in text</div>
?
class Practise extends Component {
state = { show: false };
componentDidMount() {
setTimeout(() => {
this.setState({ show: true });
}, 2000);
}
render() {
if (!this.state.show) return <div>default regular text</div>;
return <div>fading-in text</div>;
}
}
(请不要使用图书馆解决方案,我想在本地解决这个问题)
答案 0 :(得分:2)
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});
答案 1 :(得分:2)
我尝试在“原因”评论部分回答您的问题(这个问题:可以使用不透明度和过渡而不是关键帧来完成...”) 据我所知,我们必须使用添加一个触发器来进行过渡(例如 CSS 中的悬停伪类或反应事件中的 onMouseEnter 和 onMouseLeave 道具)
这是我的答案,我已经测试过了
import React, {useState} from 'react'
function App() {
const [isHovered, setIsHovered] = useState(false)
return (
<div
style={{
backgroundColor: isHovered ? 'orange' : 'green',
opacity: isHovered ? 1 : 0,
height: isHovered ? 400 : 200,
width: isHovered ? 400 : 200,
transition: 'all 1s',
}}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
</div>
);
}
export default App;
答案 2 :(得分:1)
你在特定的时间之后将show从false变为true,这不会影响淡出效果。
相反,在经过一段时间后你必须change opacity 1 to 0
。当不透明度为0
时。您可以设置show: true