var Hello = React.createClass({
getInitialState: function() {
return {
gridIsLoaded: true
}
},
animate(self) {
console.log('animating...');
$('#loadingDiv').animate({'opacity': '0'}, 500, function(){
$('#loadingDiv').animate({'opacity': '.5'}, 500, function(){
$('#loadingDiv').animate({'opacity': '1'}, 500, function(){
//if(!self.state.gridIsLoaded){
self.animate();
//}
});
});
});
},
getData() {
console.log('getData called.');
var artificialTimeout = 5000;
var self = this;
self.animate(self);
$.ajax({
url:'/echo/js/?js=hello%20world!',
complete: function (response) {
console.log(response.responseText);
setTimeout(function() {
self.setState({gridIsLoaded: true});
}, artificialTimeout);
},
error: function () {
console.log('there was an error!');
self.setState({gridIsLoaded: true});
},
});
return false;
},
handleClick(){
console.log('handleClick');
this.getData();
this.setState({gridIsLoaded: false});
},
render: function() {
var loadingJsx;
if (!this.state.gridIsLoaded) {
loadingJsx = (
<div id="loadingDiv" style={{ position:'relative', 'width': '100%', 'textAlign': 'center'}} className="text-center">
Loading... please wait
</div>);
};
return <div>
{loadingJsx}
<div>
<input type="button" value="Submit" onClick={this.handleClick} />
</div>
</div>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
当我点击提交时,它应该显示“加载中请稍候...”。我希望不透明度在显示加载时动画进出。那是行不通的。然后,如果我再次单击提交,它应该做同样的事情。
我怎样才能让动画工作?
Simple case外部 react 有效。
最佳答案
一种更“ react ”的方式是在您想要动画时切换元素上的类。所以在这种情况下,我们可以在网格尚未加载时有条件地应用动画类(尽管在这种情况下它是多余的,因为这是它唯一显示的时间)。
loadingJsx = (
<div id="loadingDiv" className={this.state.gridIsLoaded ? 'text-center' : 'text-center animate'}>
Loading... please wait
</div>);
然后我分离出应用于#loadingDiv.animate 的 css,不过另一种方法是切换 style object。 .我想你也可以不断更新样式对象的不透明度属性,这更接近你正在做的事情,但它看起来更脏 imo。
#loadingDiv.animate {
opacity: 0;
animation: fadeInOut 1s infinite;
}
@keyframes fadeInOut {
0% { opacity: 0; }
50% { opacity: 1; }
100% { opacity: 0; }
}
关于javascript - 创建一个在 react 中起作用的加载动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488685/