-
Notifications
You must be signed in to change notification settings - Fork 0
state
safwan39 edited this page Apr 28, 2021
·
7 revisions
class CustomComponent extends Component{
var $state = ['counter' => 1];
function componentDidUpdate($prevState, $currState){} //run only when there's state update
function render(){
$counter = $this->state->counter;
return new div([
new div("my state: $counter"),
new button("increment state", ['onclick'=> "this.setState({counter: ".($counter+1)."})"])
]); //must wrap the component with html tag
}
}class CustomComponent extends Component{
var $state = ['counter' => 1];
function componentDidUpdate($prevState, $currState){} //run only when there's state update
function render(){
$counter = $this->state->counter;
return new div([
new div("my state: $counter"),
new button("increment state", ['onclick'=> "this.setState(prevState => ({counter: prevState.counter +1 }))"])
]); //must wrap the component with html tag
}
}class CustomComponent extends Component{
var $state = ['counter' => 1];
function render(){
$counter = $this->state->counter;
return new div([
new div($counter, ['id'=> 'counter']),
new button("increment state", ['onclick'=> "var state = this.getState(); document.getElementById('counter').innerText = state.counter + 1 "]) //second param of set state
]);
}
}there's issue when re-rendering component the input loses the focus
to handle that we must add key prop to the input tag
class CustomComponent extends Component{
var $state = ['counter' => 1];
function render(){
$counter = $this->state->counter;
return new div([
new input(['value'=> $counter, 'type'=> 'number', 'onkeyup'=> 'this.setState({counter: parseInt(this.value)})']),
]);
}
}class CustomComponent extends Component{
var $state = ['counter' => 1];
function componentDidUpdate($prevState, $currState){} //run only when there's state update
function render(){
$counter = $this->state->counter;
return new div([
new div("my state: $counter"),
new button("increment state", ['onclick'=> "this.disabled=true; this.setState(prevState => ({counter: prevState.counter +1 }), ()=> this.disabled=false)"]) //second param of set state
]);
}
}