Callbacks
The first :ruby
-filter block will be evaluted in
the class scope of the component, which inherits
Mayu::Component::Base
.
This is where you:
Import components or other resources
Define the initial state
Define lifecycle methods
Define callback handlers
Attributes starting with on
will automatically be bound to handlers.
:ruby
def handle_click(event)
Console.logger.info(self, event)
end
%div
%p Hello world
%button(onclick=handle_click) Click me
The above code will be transformed into the following Ruby code.
def handle_click(e)
Console.logger.info(self, e)
end
public def render
Mayu::VDOM::H[
:button,
"Click me",
**mayu.merge_props({ onclick: mayu.handler(:handle_click) })
]
end
Here is the equivalent React implementation. Note that it is a class component. Mayu components are classes and don’t need hooks because it’s so easy to make a stateful class component.
import { Component } from 'react'
export default class MyComponent extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
console.log("MyComponent", e)
}
render() {
<button onClick={this.handleClick}>Click me</button>
}
}