When to change an object contained in the state of a component in React I particularly like to separate the assignments so as not to have the problem of confusing what is to be changed, and the <input>
place the property name
with the name of the same key being changed, and there the handleChange
will be useful by the dynamic factor in your code, note that the change code becomes much simpler doing so:
class App extends React.Component {
constructor() {
super();
this.state = {
equipe: {
nome: '',
idade: 0
}
}
this.handleChange =
this.handleChange.bind(this);
}
handleChange(e) {
let state = this.state;
state.equipe[e.target.name]= e.target.value
this.setState(state);
}
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<input type="text"
name="nome"
value={this.state.equipe.nome}
onChange={this.handleChange} />
<input type="text"
name="idade"
value={this.state.equipe.idade}
onChange={this.handleChange} />
</div>
)
}
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>
and in this example I put another key so that you understand that now the method will serve as a change to other text boxes, always remembering to add the name in <input>
.
You could do it your way:
class App extends React.Component {
constructor() {
super();
this.state = {
equipe: {
nome: '',
idade: 0
}
}
this.handleChange =
this.handleChange.bind(this);
}
handleChange(e) {
const inputChange = {[e.target.name]: e.target.value};
this.setState(state => ({
equipe: {
...state.equipe,
...inputChange
}
}))
}
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<input type="text"
name="nome"
value={this.state.equipe.nome}
onChange={this.handleChange} />
<input type="text"
name="idade"
value={this.state.equipe.idade}
onChange={this.handleChange} />
</div>
)
}
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>
can be displayed the initial state you created?
– novic
Forehead
onChange={this.handleChange.bind(this)}>
– Sergio