反应-使用回调函数将数据从子级传递到父级

时间:2020-08-17 16:16:46

标签: reactjs callback

我目前正在制作一个简单的下拉菜单,在其中我希望将某些状态值传递给它的父级,以便父级将从后端获取数据。

我已经在我的父函数中编写了一个回调函数,作为道具传递给孩子;但是,当我在控制台上记录更改时我没有得到任何输出,因此我认为我没有正确使用回调。 这是我的下拉菜单:

class Dropdown extends Component {
  constructor(props) {
    super(props);
  
    this.state = {
      headerTitle: this.props.title,
      teams: this.props.teams,

    };
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(teamID) {
      this.setState({
        headerTitle: this.state.teams[teamID].name
      })

  }

  render() {
    return (
      <div className="btn-group w-100 d-flex">
        <button type="button" className="btn-success w-100 dropdown-toggle" data-toggle="dropdown" onChange={this.props.handleTeam}>
          {this.state.headerTitle}
        </button>
        <ul className="dropdown-menu pre-scrollable w-100" role="menu">
          {this.state.teams.map((team) => {
            return (
              <li>
                <a href="#/game-pred" className="dropdown-item d-flex justify-content-center" onClick={() => this.handleClick(team.id)} >{team.name}</a>
              </li>
            );
          })}
        </ul>

      </div>
    );
  }
}

这是我的父母

class GamePrediction extends Component {
  constructor(props){
    super(props);
    this.state = {
      teams: [],
      count: 0,
    };
    this.handleTitleChange = this.handleTitleChange.bind(this);
  }

  handleTitleChange(newTitle) {
    if (this.state.count == 2){
      this.setState({
        teams: [newTitle,this.state.teams[1]]
      })
    }
    else if (this.state.count == 1) {
      this.setState({
        teams: [this.state.teams[0],newTitle],
        count: 2
      })
    }
    else {
      this.setState({
      teams: teams.push(newTitle),
      count: this.state.count + 1
    })
    }
    console.log("Change!",this.state.teams,this.state.count)
  } 
  render() {
        
    return (
      <div className="button-group w-100 d-flex" >
        <Dropdown title="Team 1" teams={teams} handleTeam={this.handleTitleChange} ref="team1"/>
        <Dropdown title="Team 2" teams={teams} ref="team2"/>
        
      </div>
    );
  }
}

还应注意,如果有帮助,用户可以从两个下拉菜单中为每个下拉菜单选择一个团队。

1 个答案:

答案 0 :(得分:0)

<button>具有onClick,而不是onChange

所以您可能要更改此内容

<button type="button" className="btn-success w-100 dropdown-toggle" data-toggle="dropdown" onChange={this.props.handleTeam}>

对此

<button type="button" className="btn-success w-100 dropdown-toggle" data-toggle="dropdown" onClick={this.props.handleTeam}>

我还看到您的handleTitleChange(newTitle)接受了newTitle参数,您可以像这样传递该参数

<button type="button" className="btn-success w-100 dropdown-toggle" data-toggle="dropdown" onClick={() => this.props.handleTeam('My new Title')}>