Hi, I will share one simple code of React for our good coding exercise .
One of the big advantages of React is that we can define HTML as a component and use them.
But, if such HTML components include check boxes, it should be managed its statement like “-checked” or “-un-checked”.
How to mange React component’s statement
These components need to have the values of the statements. A “state” object handles the statements.
- “state” object holds the statement value
- setState() method updates the value of the “state” object.
- “render()” is method automatically run when the statement has been changed.
Sample code
The clock is created as a component inside the sample code. When we regard the clock’s seconds as one state, the clock can be taken as “the component which statement has been updated per second”.
After execution of the code
Just drop the html file that you created on your web browser. The sample code will be run and the hour, minute and second will be displayed.
What the code does?
These parts A to E inside the code mean following.
A part
Identifies clock component which has its statement by using “class”.
B part
Resets the component statement. And “Date” object that obtains current time is set to “now” property.
C part
Updates the state of clock seconds. The function “setInterval()” will work to set the timer to update the state per second. “setState()” method updates the “now” property. Executing “setState()” means the statement of the component has been updated.
D part
Identifies “render()” to return the contents of rendering.
E part
Allocates the component “SClock” to DOM.
コメント