子更新父状态不起作用

时间:2017-09-27 13:30:50

标签: reactjs

我正在尝试让navBar更新主要组件。

class NavBar extends Component{

  constructor(props){
    super(props);
  }

  clickHandler(handlerCode){
    this.props.handleClick(handlerCode);
  }

  render(){
    var self = this;
    var options = this.props.options;
    var listItems = options.map(function(data, index){
      return (<li key={'navBar.' + index} onClick={() => self.clickHandler(data.handlerCode)}>{data.name}</li>);
      });
    return (<ul>{listItems}</ul>);
  }
}

class Student extends Component {
  //This class will create the entire student interface
  //It will retrieve data from the server
  //However, there will be two subclass (StudentNavBar and StudentView)
  //That will render the data necessary to do this


  constructor(){
    super();
    this.state = {
      currentView: 'simplified',
      simplifiedViewData: {
        monday: "Study Hall",
        tuesday: "Computer Science Club",
        wednesday: "Science Enrichment",
        thursday: "Hawkeye",
        friday: "Hurtado Food Pantry",
      },
      navBar : [
        {name: "Sign Up", handlerCode: "signup" ,},
        {name: "Quick", handlerCode: "simplifiedView", },
        {name: "Detailed" , handlerCode: "detailedView" ,},
        {name: "Logout" , handlerCode:"logout"},
      ],
    }
    this.state.children = <StudentView viewData={this.state.simplifiedViewData} view={'none'} />; //will probably default to simplified, but for testign
  }

  render(){
    var self = this;
    return (<div><NavBar handleClick={self.handleClick} options={this.state.navBar} />{this.state.children}</div>);
  }

  handleClick(input){
    if(input == 'simplifiedView'){
      console.log(this);
      this.state.children = <StudentView viewData={this.state.simplifiedViewData} view={'simplifiedView'} />;
    }
  }
}

但是,当从NavBar类调用handleClick()事件时,这被视为NavBar组件而不是StudentView。由于子组件没有状态(我应该更改吗?),它会抛出错误。我该如何纠正这个?

1 个答案:

答案 0 :(得分:1)

您必须将事件处理程序绑定到组件。

在你的构造函数中:

this.handleClick = this.handleClick.bind(this);

您的render功能:

render(){
    return (<div><NavBar handleClick={this.handleClick} options={this.state.navBar} />{this.state.children}</div>);
}