Converting a Function to a Class
文章目录

React: Converting a Function to a Class.md

Converting a Function to a Class

  • You can convert a functional component like Clock to a class in five steps:
  • Create an ES6 class with the same name that extends React. Component.
  • Add a single empty method to it called render().
  • Move the body of the function into the render() method.
  • Replace props with this.props in the render() body.
  • Delete the remaining empty function declaration.
1
2
3
4
5
6
7
8
9
10
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Adding Local State to a Class

We will move the  date   from props to state in three steps:

  1. Replace  this.props.date   with  this.state.date   in the  render()   method:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Clock extends React.Component {
render() {
return ( <
div >
<
h1 > Hello, world! < /h1> <
h2 > It is {
this.state.date.toLocaleTimeString()
}. < /h2> <
/div>
);
}
}
  1. Add a  class constructor  that assigns the initial  this.state :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Clock extends React.Component {
  constructor(props) {  //!!!!!!!!!!!!!!
    super(props);
    this.state = {datenew Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Note how we pass  props   to the base constructor:

1
2
3
4
  constructor(props) {
    super(props);
    this.state = {datenew Date()};
  }

Class components should always call the base constructor with  props .

  1. Remove the  date   prop from the  <Clock />   element:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

``` jsx

We will later add the timer code back to the component itself.

The result looks like this:

``` jsx
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {datenew Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

Reference

https://reactjs.org/docs/state-and-lifecycle.html