This example shows how to develop the React component in CodePen. Use this example as a study note. First look at the code:

//HTML <div id="root"> <! -- This element's contents will be replaced with your component. --> </div> //JS function FormattedDate(props) { return <h2>It is {props.date.toLocaleTimeString()}.</h2>; } class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div> <h1>Hello, world! </h1> <FormattedDate date={this.state.date} /> </div> ); } } function App() { return ( <div> <Clock /> <Clock /> <Clock /> </div> ); } ReactDOM.render(<App />, document.getElementById('root'));Copy the code

The running process of the program:

Define a div with id root in HTML

ReactDOM. Render div with id root using App

What does the function App return? Not strings, not HTML, but JSX, which is an extension of JavaScript syntax. Babel compiles JSX into a call to React. CreateElement ()

4. In the layout returned by App, there are three Clock components. The Clock component inherits react.component. when passed into reactdom. render, the Clock constructor will be called

The Clock constructor accepts props, which holds properties of the component. No properties are passed in. Initialize the state of the component in the constructor, and set the date field to the state

Render JSX = JSX; render JSX = JSX; render JSX = JSX; Get the date passed in by props. Date in the FormattedDate function

7, at this point you can already see the three Clock display time

8. How does the time update automatically? ComponentDidMount is triggered when Clock is inserted into the DOM, and componentWillUnmount is triggered when Clock is removed from the DOM, so periodic updates start when componentDidMount is called, Update regularly when componentWillUnmount is off

9, Scheduled update will call the TICK method, tick method calls setState to update the date field

The setState method triggers a re-call of the Render method to update the time

As the author was engaged in mobile terminal development before, the concept of React component is basically the same as the concept of iOS and Android View, and even some methods can be corresponding. ComponentDidMount and componentWillUnmount can be corresponding to onAttachedToWindow and onDetachedFromWindow in Android View. Render in Clock corresponds to onDraw in Android View. You can see that the programming philosophy is pretty much the same. Componentization is actually modularization, which improves the reusability and maintainability of code.