2017-08-24 3 views
4

Dies ist meine Reaktion Komponente:Wie machen diese verfügbar Funktion innerhalb machen

constructor(props) { 
    super(props); 

    this.state = { 
    }; 
    this.showChart = this.showChart.bind(this) 
} 

showChart() { 
    console.log('test') 
} 

render() { 

    {this.showChart} //throws error that, this is undefined 

    return() (
     {this.showChart} //prints test 
    ) 
} 

Nun, wenn ich die Funktion von render() aber außerhalb return() was soll ich tun nennen wollen?

Antwort

5

Die Komponentensyntax ist an einigen Stellen nicht korrekt. this ist in Render verfügbar.

constructor(props) { 
    super(props); 

    this.state = { 
    }; 
    this.showChart = this.showChart.bind(this) 
} 

showChart() { 
    console.log('test') 
} 

render() { 

    this.showChart() 

    return ( 
     <div>{this.showChart()}</div> 
) 

} 

EDIT:

Sie können auch mit Pfeil Funktionen zusammenarbeiten, um die Funktionen zu binden, um Ihre Komponente. Auf diese Weise müssen Sie nicht jede Funktion bind. Es sieht viel sauberer:

constructor(props) { 
    super(props); 

    this.state = { 
    }; 
} 

showChart =() => { 
    console.log('test') 
} 

render() { 

    this.showChart() 

    return ( 
     <div>{this.showChart()}</div> 
) 

} 
+0

Yeah du hast Recht –

+0

Glücklich, dass es dir geholfen hat –

0

ersetzen {this.showChart} mit this.showChart() innerhalb der Funktion machen. Dein neuer Code sollte also

sein
render(){ 
this.showChart(); 

return(
     {this.showChart}  
); 
} 
Verwandte Themen