在React JS中重新排序列表元素 [英] Reordering list element in react js

查看:140
本文介绍了在React JS中重新排序列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何重新排序列表元素.就像您有一个元素li的列表,然后将最后一个元素放在第一位一样,第10个索引将放置在0索引中

I am wondering how to re order a list element. Its like you have a list of an elements li and put the last element in the first place like the index of 10th would be placed in the index of 0

React.render(   <div>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li> //When an event fires, this item would go up to the first index   </div>,   document.getElementById('example') );

推荐答案

基于您对Abdennour答案的评论(无论位置如何,您都需要更新一个项目),您无法使用简单数字数组进行此类操作,您需要索引您的值:

Based on your comment on Abdennour answer (you need to update an item regardless of its position), you cannot do such operation with an array of simple numbers, you need to index your values:

class MyList extends Component {

  render() {
    return(
      <ul>
         {this.props.items.map((item ,key) => 
             <li key={key}> {item}</li>
          )}
      </ul>
    )
  }

}


class App extends React.Component{

    constructor(props) {
      this.state= {
        listItems: [{id: 1, val: '1'}, {id: 2, val: '2'}, {id: 2, val: '2'}, {id: 3, val: '3'}]
      };
    }

    reverse = () => {
       this.setState({
         listItems: this.state.listItems.reverse()
       });
    }

    // You can ignore this, simple put some random value somewhere
    // In your case this would be the function that changes the value of one of the items, should of course be NOT random
    changeRandom = () => {
      const index = Math.floor(Math.random() * this.state.listItems.length);
      const newList = this.state.listItems.slice();
      newList[index] = Math.floor(Math.random() * 10).toString();

      this.setState({
        listItems: newList
      })
    }

    render() {
      return (
        <div>
          <div>
             <MyList items={this.state.listItems.map(item => item.val)} />
          </div>
          <div> 
             <button onClick={reverse}>Reverse</button>
          </div>
          <div> 
             <button onClick={changeRandom}>Random Change</button>
          </div>

        </div>

       )
    }
}

这篇关于在React JS中重新排序列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆