Sono nuovo per reagire e provare a creare una semplice applicazione ToDo basata su react-starter-kit. Sto usando le classi ES6 e non riesco a trovare un modo per aggiornare lo stato genitore da un componente figlio.Reazione di stato dei componenti figlio secondario ES6
Ecco il codice:
import React, { PropTypes, Component } from 'react';
import withStyles from '../../decorators/withStyles';
import styles from './ToDoPage.less';
@withStyles(styles)
class ToDoPage extends Component {
static contextTypes = {
onSetTitle: PropTypes.func.isRequired
};
constructor() {
super();
this.state = {
items: ['Item1', 'Item2'],
value: ''
};
}
updateValue(newValue) {
//this.state is null here
this.setState({
value: newValue
});
}
clickHandler() {
console.log('AddToDo state:', this.state)
if (this.state.value && this.state.items) { //this.state is null here
this.setState({
items: this.state.items.push(this.state.value)
});
}
}
render() {
let title = 'To Do List';
this.context.onSetTitle(title);
return (
<div className="ToDoPage">
<div className="ToDoPage-container">
<h1>{title}</h1>
<AddToDoTextBox handleUpdate={this.updateValue}/>
<AddToDoButton handleClick={this.clickHandler}/>
<div className = "todo-items">
<br/>
<div>({this.state.items.length}) items found.</div>
<ToDoList items = {this.state.items}/>
</div>
</div>
</div>
);
};
}
class ToDoList extends Component {
static propTypes = {
items: PropTypes.array.isRequired
};
render() {
console.log(this.props.items);
return (
<ul>
{this.props.items.map(function(item) {
return <li key={item}>{item}</li>
}) }
</ul>);
};
};
class AddToDoButton extends Component {
static propTypes: {
clickHandler: React.PropTypes.func
}
constructor() {
super();
}
render() {
return (<button
className="btn btn-primary"
onClick={this.props.handleClick.bind(this)}>Add ToDo</button>);
};
}
class AddToDoTextBox extends Component {
static propTypes: {
handleUpdate: React.PropTypes.func
}
constructor() {
super();
this.state = {
value: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({value: e.target.value});
this.props.handleUpdate.call(this, e.target.value);
}
render() {
return <input type="text" placeholder="Enter todo item here" size="50" onChange={this.handleChange}/>
};
}
export default ToDoPage;
voglio accedere lo stato di ToDoPage da UpdateValue() e clickHandler() funzioni, ma this.state è nullo mentre il legame con i componenti figlio essi vengono chiamati da (cioè AddToDoButton e AddToDoTextBox). Come posso accedere/aggiornare lo stato di ToDoPage da clickHandler() o updateValue()?
possibile duplicato del [Reagire ref e setState che non funziona con ES6] (http : //stackoverflow.com/questions/29577977/react-ref-and-setstate-not-working-with-es6) – loganfsmyth