2017-09-27 6 views
0

Ich versuche, eine navBar aktualisieren die Hauptkomponente.Child update parent state funktioniert nicht

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'} />; 
    } 
    } 
} 

Wenn jedoch jemals die handelt() Ereignis aus der NavBar Klasse aufgerufen wird, wird dies als NavBar Komponente behandelt und nicht den StudentView. Da die untergeordnete Komponente keinen Status hat (sollte ich das ändern?), Wird ein Fehler ausgegeben. Wie würde ich das korrigieren?

Antwort

1

Sie müssen den Event-Handler an die Komponente binden.

In Ihrem Konstruktor:

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

Und Ihre render Funktion:

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

Vielen Dank für diese –

Verwandte Themen