javascript - react : What happens on consecutive renders where a list shuffles?

标签 javascript html css-animations reactjs

我正在尝试创建一个用一些动画随机洗牌的列表。

这里是the fiddle对于它,我使用 key 属性来识别每个 child 。

http://jsfiddle.net/1wcpLLg4/

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/

相关文章:

html - 为什么我的 animate.css 动画在 Chrome 中有效,但在 Firefox 中无效?

javascript - 使用 load() 加载 html 页面后,jQuery 单击事件处理程序不起作用

javascript - (Javascript)为什么捕获没有捕获到拒绝?

javascript - 通过 React Native 更改图标 activeIndex

html - Firefox CSS3 动画根本不起作用

html - CSS3 animation-delay 属性不工作

javascript - 为什么这个数组中的值(显然)立即改变

php - 从 PHP 插入多个 MySQL 时出现问题

javascript - php mail() 在填写表单之前发送邮件

javascript - 如何滚动以自动滚动到可编辑div onload的底部