N
N
Neuro2019-07-08 13:45:41
JavaScript
Neuro, 2019-07-08 13:45:41

Why did the variable declared in ComponentWillMount become Undefined?

I have a component of this type, for brevity I removed everything unnecessary.

'use strict';
class LoginFormComponent extends React.Component {

  handleSubmit() {
    console.log(this.model); //undefined
  }

  componentWillMount() {
    this.model = 123;
  }

  render() {
                console.log(this.model);  //123
    var styles = this.props.styles;

    return (
            <CM.MUI.FlatButton
            style={styles.buttonStyle}
            onClick={this.handleSubmit}
            label={CM.gettext('Login')}/>
    );
  }
};

module.exports = LoginFormComponent;

This component displays a button, when clicked, the value of the variable that I declared in ComponentWillMpont should be displayed in the console, but when clicked, undefined is displayed in the console, why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
smilingcheater, 2019-07-08
@Riveran

Because by writing onClick={this.handleSubmit} you take the function out of context, and in this function you have this - not your component
Try writing
onClick={this.handleSubmit.bind(this)}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question