如何通过setInterval
使元素更改状态?
尝试以随机位置渲染元素并尝试按位置更改位置更改:
var Elem = React.createClass({
render: function () {
return (
<h1 className="elem">
Hello, {this.props.name} !
</h1>
);
}
});
var MainContainer = React.createClass({
componentDidMount: function () {
setInterval(this.shf, 777);
},
getInitialState: function () {
return {source: []};
},
shf: function () {
var source = this.props.source.sort(function () {
return .5 - Math.random();
});
this.setState({
source: source
});
},
render: function () {
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var Elems = this.state.source.map(function (elem, i) {
return (
<ReactCSSTransitionGroup key={i * 10}
transitionName="example"
transitionAppear={true} transitionAppearTimeout={500}
transitionEnter={true} transitionLeave={true}>
<Elem key={i} number={i} name={elem}/>
</ReactCSSTransitionGroup>
);
}, this);
return (
<div>
{Elems}
</div>
);
}
});
ReactDOM.render(<MainContainer source={["bill", "bob", "sam", "john", "smith"]}/>,
document.getElementById('container'));
CodePen链接样式:http://codepen.io/anon/pen/ZOQmJX
它是第一次渲染的动画,但不是每个州的变化,如何实现它?
答案 0 :(得分:0)
componentDidMount: function () {
setInterval(this.shf, 777);
}
=&GT;
componentDidMount: function () {
setInterval(()=>this.shf(), 777);
}
调用setState时,this.state.source已更改,但ReactCSSTransitionGroup节点的子节点没有更改,五个节点具有相同的键和相同的序列。
render: function () {
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var Elems = this.state.source.map(function (elem, i) {
return (
<Elem key={elem} number={i} name={elem}/>
);
}, this);
return (
<ReactCSSTransitionGroup
transitionName="example"
transitionAppear={true} transitionAppearTimeout={500}
transitionEnter={true} transitionLeave={true}>
{Elems}
</ReactCSSTransitionGroup>
);
}
或仅更改
<Elem key={elem} number={i} name={elem}/>