在react js中重新排序列表元素

时间:2017-01-28 03:00:30

标签: reactjs reorderlist

我想知道如何重新排序列表元素。它就像你有一个元素列表@PublishedApi并把最后一个元素放在第一个位置,就像第10个索引将放在0的索引中

li

2 个答案:

答案 0 :(得分:2)

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

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>

       )
    }
}

答案 1 :(得分:1)

所以,我假设你有两个React组件:一个用于列表,另一个是主要组件(App),其中包含list以及反转列表的按钮。

&#13;
&#13;
class MyList extends React.Component {

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

}
MyList.defaultProps= {items:[]};


class App extends React.Component{
    
    state= {
        listItems: ['1', '2', '3', '4']
     };

    onClick(e) {
       e.preventDefault();
       this.setState({
         listItems: this.state.listItems.reverse()
       });
    }

    render() {
      return (
        <div>
          <div>
             <MyList items={this.state.listItems} />
          </div>
          <div> 
             <button onClick={this.onClick.bind(this)}>Reverse</button>
          </div>
        
        </div>
        
       )
    }
}

ReactDOM.render(<App /> ,  document.getElementById('example'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section id="example" />
&#13;
&#13;
&#13;