在React中使用Object而不是class

时间:2016-12-21 11:38:18

标签: javascript reactjs ecmascript-6

我是JavaScript和React的新手。我正在修改以下代码以使用JavaScript对象而不是类。我被困了,因为我不理解第7行中的代码,以及为什么会抛出错误。

import React from 'react';

function AwesomeComponent(props) {
    // instead of class AwesomeComponent exnteds React.Component
    AwesomeComponent = Object.assign(Object.create(React.Component.prototype))
    AwesomeComponent.props = props
    AwesomeComponent.state = { likesCount: 0 };
    this.onLike = this.onLike.bind(this);   // here's my problem. LINE 7

    onLike()
    let newLikesCount = this.state.likesCount + 1;
    this.setState({ likesCount: newLikesCount });

    AwesomeComponent.render = function() {
        return (
          <div>
            Likes : <span>{this.state.likesCount}</span>
            <div><button onClick={this.onLike}>Like Me</button></div>
          </div>
        );
    }
}

export default AwesomeComponent;

以下是抛出的错误:

AwesomeComponent.jsx:7 Uncaught TypeError: Cannot read property 'onLike' of undefined
    at AwesomeComponent (AwesomeComponent.jsx:7)
    at ReactCompositeComponent.js:306
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:305)
    at ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:280)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:188)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactDOMComponent.mountChildren (ReactMultiChild.js:238)
    at ReactDOMComponent._createInitialChildren (ReactDOMComponent.js:691)
    at ReactDOMComponent.mountComponent (ReactDOMComponent.js:516)

1 个答案:

答案 0 :(得分:0)

试试这个

   import React from 'react';

    class AwesomeComponent extends React.Component {

      constructor(props) {
        super(props);
        this.state = {likesCount : 0};
        this.onLike = this.onLike.bind(this);
      }

      onLike () {
        let newLikesCount = this.state.likesCount + 1;
        this.setState({likesCount: newLikesCount});
      }

      render() {
        return (
          <div>
            Likes : <span>{this.state.likesCount}</span>
            <div><button onClick={this.onLike}>Like Me</button></div>
          </div>
        );
      }

    }

    export default AwesomeComponent;