react.js call parent function from child

前端 未结 3 2082
小蘑菇
小蘑菇 2021-01-12 02:16

I know there are a few similar questions here and here but I am having a tough time understanding what is the correct thinking today on this and extrapolating it to my situa

相关标签:
3条回答
  • 2021-01-12 02:19

    call parent function from child

    You don't (like what the other posts say). You pass handleScoreRemove into the child as a prop. Inside the child, you call the function by calling the prop. In the following, handleScoreRemove is passed as the onScoreRemove prop inside the child.

    <Score ...stuff... onScoreRemove={this.handleScoreRemove}></Score>
    

    You're already doing the same thing with the ScoreBox (parent) and ScoreForm (child). You're passing a reference of handleScoreSubmit as onScoreSubmit prop in the child.

    <ScoreForm onScoreSubmit={this.handleScoreSubmit} />
    
    0 讨论(0)
  • 2021-01-12 02:21

    You need to pass handleScoreRemove through props

    var scoreNodes = this.props.data.map(function(score) {
      return <Score
        key={score.id}
        id={score.id}
        team1_name={score.team1_name}
        team1_score={score.team1_score}
        team2_name={score.team2_name}
        team2_score={score.team2_score}
        handleScoreRemove={this.handleScoreRemove.bind(this)}>
      </Score>
    }, this);
    

    and in Score component call it like this

    removeRecord: function(e) {
       this.props.handleScoreRemove( /* add arguments what do you need */ );
    },
    
    0 讨论(0)
  • 2021-01-12 02:37

    You should pass handleScoreRemove as a prop to Score:

    In ScoreList:

    var scoreNodes = this.props.data.map(function(score) {
      return (
        <Score key={score.id} (...) handleScoreRemove={this.handleScoreRemove}>
        </Score>
      );
    });
    

    In Score:

    removeRecord: function(e){
      this.props.handleScoreRemove(this);
    }
    
    0 讨论(0)
提交回复
热议问题