React.js - Implementing sorting of components

后端 未结 1 1151
星月不相逢
星月不相逢 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 <div/> in <Sort/> on clicking which it calls a parent function this.props.sortBy()

    class Sort extends React.Component {
      sort(field){
        this.props.sortBy(field);
      }
      render() {
        return (
          <div className="sort-section">
            <h1>Sort by</h1>
            <div className="pill" id='age' onClick=this.sort.bind(this,'age')>Age</div>
            <div className="pill" id='Meters' onClick=this.sort.bind(this,'height')>Height</div>
            <div className="pill" id='Name' onClick=this.sort.bind(this,'name')>Name</div>
          </div>
        )
      }
    }
    

    Pass this parent function sortBy as props from your <SortablePlayerTable/> 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 (
          <div>
            {/* some JSX */}
            <Sort sortBy={sortBy}/>
            <Roster 
                    players={this.state.players} 
            />
          </div>
        );
      }
    };
    

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

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