React.js - Implementing sorting of components

后端 未结 1 1155
星月不相逢
星月不相逢 2020-12-13 16:56

I\'m trying to learn React concepts, especially re: state and dynamic UIs, by coding a small sports roster-like UI. I\'ve included the code below and the whole app + visual

1条回答
  •  半阙折子戏
    2020-12-13 17:05

    Attach a function to each

    in on clicking which it calls a parent function this.props.sortBy()

    class Sort extends React.Component {
      sort(field){
        this.props.sortBy(field);
      }
      render() {
        return (
          

    Sort by

    Age
    Height
    Name
    ) } }

    Pass this parent function sortBy as props from your component.

    class SortablePlayerTable extends React.Component {
      state = {
       players: [] // default state
      }
      sortBy(field){
        // Your sorting algorithm here
        // it should push the sorted value by field in array called sortedPlayers 
        // Then call setState
        this.setState({
          players: sortedPlayers
        });
      }
      render() {
        // calculate stats
        return (
          
    {/* some JSX */}
    ); } };

    Now the sorted array will be available to your component as this.props.players. Render the array directly without applying any sort inside component.

    0 讨论(0)
提交回复
热议问题