Sto lavorando con ReactJS con ES6, ma ho alcuni problemi a comunicare child> parent attraverso gli oggetti di scena. Esempio del mio approccio:ReactJS con ES6: this.props non è una funzione quando comunico due componenti
class SearchBar extends React.Component {
handler(e){
this.props.filterUser(e.target.value);
}
render() {
return <div>
<input type='text' className='from-control search-bar' placeholder='Search' onChange={this.handler} />
</div>
}
}
export default class User extends React.Component {
constructor(props) {
super(props);
this.state = {name: '', age: '', filter: ''};
}
filterUser(filterValue){
this.setState({
filter: filterValue
});
}
render() {
return <div>
<SearchBar filterUser={this.filterUser} />
<span>Value: {this.state.filter}</span>
</div>
}
}
Questo restituisce Uncaught TypeError: this.props.filterUser is not a function
.
Qualche idea? Forse vincolante?
[EDIT] Solution (Grazie @knowbody & @Felipe Skinner):
mi mancava vincolante nel mio costruttore. Il binding nel costruttore di SearchBar funziona perfettamente.
Utilizzando React.createClass()
(ES5), esegue automaticamente le associazioni su this
per le proprie funzioni. In ES6 è necessario associare manualmente this
. Maggiori informazioni https://facebook.github.io/react/docs/reusable-components.html#es6-classes
Bello! funziona, ma genera un errore "token imprevisto" impostando i propTypes in questo modo. 'SearchBar.propTypes = { filterUser: React.PropTypes.func };' funziona meglio. – skozz
mi dispiace aggiustarlo, quello che ho usato prima è il modo ES7 https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es7-property- inizializzatori – knowbody
Sì, certo. Ad ogni modo questo funziona senza impostare propTypes, hai ragione: mi mancava l'associazione nel mio costruttore. Il binding nel costruttore di SearchBar funziona perfettamente. – skozz