Public Class Fields allow you to add instance properties to the class definition with the assignment operator (=
). In this lesson, we'll look at their use case for simplifying event callbacks and state initialization with a React component.
Handle function:
// Better handleClick = () => { ... } // Not good constructor() { super(); this.handleClick = this.handleClick.bind(this); } handleClick() { ... }
Handle State:
// Better state = {count: 0} // Not good constructor() { super(); this.state = {count: 0}; }
Using puiblic field, we can actually remove 'constructor' because it is no longer necessary.
class App extends React.Component { state = {clicks: 6} handleClick = () => { this.setState(prevState => { return {clicks: prevState.clicks + 1} }) } render() { return ( <div> <div> Click Count: {this.state.clicks} </div> <button onClick={this.handleClick} > Click Me! </button> </div> ) } } ReactDOM.render( <App />, document.getElementById('root') )