我正在尝试创建一个用一些动画随机洗牌的列表。
这里是the fiddle对于它,我使用 key
属性来识别每个 child 。
var ListAnimate = React.createClass({
list: [
{id: 1, caption: "Hello"},
{id: 2, caption: "There"},
{id: 3, caption: "Whatsup"},
{id: 4, caption: "Sanket"},
{id: 5, caption: "Sahu"},
],
shuffle: function() {
this.list.shuffle(); // Shuffles array!
this.forceUpdate();
},
render: function() {
return <div>
<button onClick={this.shuffle}>Shuffle</button>
<ul>
{this.list.map(function(el, i){
return <li key={el.id} style={ {top: (i*60)+'px'} }>{el.caption} {el.id}</li>;
})}
</ul>
</div>;
}
});
React.render(<ListAnimate />, document.body);
来自React docs about Dynamic Children ,它指出使用 key
属性是为了在连续渲染期间识别数组中的元素。因此,刚刚重新排序的项目不得卸载并安装到新位置,而应该重新定位它们,但似乎不会发生在 fiddle 中,其中列表顶部的节点始终是正在卸载并安装在不同的位置。
但是底部的元素似乎与动画配合得很好。
最佳答案
请记住,对于您正在寻找的动画类型,您需要始终保持 DOM 的顺序相同,并且仅更新它们在组件的渲染函数中的位置。
我使用此策略修改了您的第一个 fiddle :http://jsfiddle.net/0maphg47/1/
render: function() {
// create a sorted version of the list to render the DOM
var sortedCopy = this.state.list.slice().sort(function(a, b) {
return a.id - b.id;
});
return <div>
<button onClick={this.shuffle}>Shuffle</button>
<ul>
{sortedCopy.map(function(el, i) {
// find the position of the element in the shuffled list
// which gives the position the element must be
var pos = this.state.list.indexOf(el);
return <li key={el.id} style={ {top: (pos*60)+'px'} }>
{el.caption} {el.id}
</li>;
}, this)}
</ul>
</div>;
}
仍有改进的空间,但我会将其留给您。
关于javascript - react : What happens on consecutive renders where a list shuffles?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457132/