What's different between two ways of defining React Component?

这一生的挚爱 提交于 2019-12-11 15:43:49

问题


There're 2 ways to define a React component.

First one is like below.

class SomeComponent extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      someState: false
    }
    this._handleOnChangeState = this._handleOnChangeState.bind(this)
  }

  _handleOnChangeState (e) {
    this.setState({ someState: e.target.value })
  }
  ....

}

Second one is like below.

class SomeComponent extends React.Component {
  state = {
    someState: false
  }

  _handleOnChangeState = (e) => {
    this.setState({ someState: e.target.value })
  }
  ....

}

These two codes are the same function, but I guess there's some different something like memory usage or etc.

Can someone make it clearly? Thanks in advance!


回答1:


This is a new proposal (class fields) for ES which is in stage 3 right now. To run a code written in this way you need a transpiler like Babel and an appropriate plugin.

Before transpile:

class A {
  static color = "red";
  counter = 0;

  handleClick = () => {
    this.counter++;
  }
}

After transpile (with stage 2 on Babel Repl):

class A {
  constructor() {
    this.counter = 0;

    this.handleClick = () => {
      this.counter++;
    };
  }

}
A.color = "red";

In addition to the official proposal 2ality blog post is a good source to see what are the details.

Here is a reddit post if you have time to read the discussion storm what is the reason behind this proposal :)

The arrow function here is a different story. You can use instance properties without constructor and mix your code with standard functions. But when you want to use something like that this won't work:

class App extends React.Component {
  state = { bar: "baz"}

  foo() { console.log(this.state.bar) };

  render() {
    return <div><button onClick={this.foo}>Click</button></div>;
  }
}

We need to bind our function in somehow like:

return <div><button onClick={this.foo.bind(this)}>Click</button></div>

But, binding our function in a JSX prop is no so good since it will create our function in each render.

One way to do this nicely bind in our constructor:

constructor(props) {
    super(props);
    this.foo = this.foo.bind( this );
  }

But, if I have to write a constructor what is the point? This is why you see arrow functions everywhere where we define the classes like your second example. No need to bind to function thanks to arrow functions. But it is not directly related to this new proposal I think.




回答2:


The first one is the traditional approach and the second one is when you babel-transform-class-properties plugin. In the second type babel does the same thing under the hood, therefore it is a matter of convenience.



来源:https://stackoverflow.com/questions/50789543/whats-different-between-two-ways-of-defining-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!