在反应js中重新排序列表元素

Reordering list element in react js

我想知道如何重新排序列表元素。就像你有一个元素列表 li 并将最后一个元素放在第一位,就像第 10 个索引将放在 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') );

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

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'))
<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" />

根据您对 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>

       )
    }
}