State Events And Managed Controls
suggest changeHere’s an example of a React component with a “managed” (controlled) input field. Whenever the value of the input field changes, an event handler updates the component state with the new value. The call to setState triggers render, which updates the component in the DOM.
import React from 'react';
import {render} from 'react-dom';
class ManagedControlDemo extends React.Component {
constructor(props){
super(props);
this.state = {message: ""};
}
handleChange(e){
this.setState({message: e.target.value});
}
render() {
return (
<div>
<legend>Type something here</legend>
<input
onChange={this.handleChange.bind(this)}
value={this.state.message}
autoFocus />
<h1>{this.state.message}</h1>
</div>
);
}
}
render(<ManagedControlDemo/>, document.querySelector('#app'));
It's very important to note the runtime behavior. Every time a user changes the value in the input field:
handleChangewill be called and sosetStatewill be called and sorenderwill be called
Pop quiz, after you type a character in the input field, which DOM elements change
- all of these - the top level div, legend, input, h1
- only the input and h1
- nothing
- what's a DOM?
You can experiment with this more here to find the answer
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents