10 Component methods
This chapter covers
- Implementing component methods to handle events
- Binding a method’s context to the component
- Passing the host component reference to mount and patch functions
What happens when you’re handling an event in a component that requires a couple of lines of code? One-liners, like this one, look fine inside the virtual Document Object Model (DOM) definition:
render() { const { count } = this.state return hFragment([ h( 'button', { on: { click: () => this.updateState({ count: count - 1 }) }} #1 ['Decrement'] ), h('span', {}, [count]), h( 'button', { on: { click: () => this.updateState({ count: count + 1 }) }} #2 ['Increment'] ) ]) }
But what happens when you want to do more than you can fit in a single line? Well, you could fit the code inside the virtual DOM (vdom) definition, but then the code will be harder to read. Look at the following example list, in which clicking a button loads more items from the server: