最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

html - TypeError: this is undefined - React JS, Javascript - Stack Overflow

matteradmin19PV0评论

I am trying to implement a simple react component which change name on clicking. I am getting the error Error - TypeError: this is undefined while loading my page which has below react component. The error seems to be in the setState line.

class Layer5 extends React.Component {
  constructor(props) {
    super(props);

    this.state = {buttonstate: false};

  }

  componentDidMount() {

  }

  componentWillUnmount() {

  }

  handleClick(e) {
    e.preventDefault();

    this.setState({buttonstate: !this.state.buttonstate});      
  }

  render() {
    var icon = this.state.buttonstate ? 'images/image1.png' : 'images/image2.jpg';

    return (
      <div className="layer5">
        <a href="#" onClick={this.handleClick}><img src={icon} ></img></a>
      </div>
    );
  }
}

I am trying to implement a simple react component which change name on clicking. I am getting the error Error - TypeError: this is undefined while loading my page which has below react component. The error seems to be in the setState line.

class Layer5 extends React.Component {
  constructor(props) {
    super(props);

    this.state = {buttonstate: false};

  }

  componentDidMount() {

  }

  componentWillUnmount() {

  }

  handleClick(e) {
    e.preventDefault();

    this.setState({buttonstate: !this.state.buttonstate});      
  }

  render() {
    var icon = this.state.buttonstate ? 'images/image1.png' : 'images/image2.jpg';

    return (
      <div className="layer5">
        <a href="#" onClick={this.handleClick}><img src={icon} ></img></a>
      </div>
    );
  }
}
Share Improve this question edited Oct 25, 2019 at 8:15 Kalle Richter 8,72829 gold badges91 silver badges203 bronze badges asked Dec 4, 2017 at 3:21 codinglovercodinglover 1991 gold badge2 silver badges12 bronze badges 2
  • on which line? chances are it's in handleClick ... common solution is to have the line this.handleClick = this.handleClick.bind(this) inside the constructor - because this is tricky with event handlers – Jaromanda X Commented Dec 4, 2017 at 3:24
  • 1 This article explains 5 different approaches to solve this issue with pros and cons: medium.freecodecamp.org/… – Liren Yeo Commented Dec 4, 2017 at 5:09
Add a comment  | 

2 Answers 2

Reset to default 18

Either a) create a property lexically closed over the instance (this) using an arrow function or b) use .bind.

Do one or the other.

either a)

class Layer5 extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = e => {
      e.preventDefault();

      this.setState({buttonstate: !this.state.buttonstate});
    };
  }
}

or b)

render() {
    const icon = this.state.buttonstate ? 'images/image1.png' : 'images/image2.jpg';

    return <div className="layer5">
        <a href="#" onClick={this.handleClick.bind(this)}>
          <img src={icon} >
          </img>
        </a>
      </div>;
  }
}

Note that some prefer to cache the bound function created by .bind but this is simply an optimization.

import React from 'react'

class UsernameForm extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        username: ''
    }
    this.onchange=this.onChange.bind(this)
    this.onSubmit=this.onSubmit.bind(this)
}
onChange(e) {
    this.setState({
        username: e.target.value
    })
}

onSubmit(e) {
    e.preventDefault()
    this.props.onSubmit(this.state.username)
}

render() {
    return (
        <div>
            <form onSubmit={this.onSubmit}>
                <input type='text'placeholder='What is your username ?' onChange={this.onChange} />
                <input type='submit' />
            </form>
        </div>
    )
}

}

export default UsernameForm

I am getting error: this is undefined

So that i bind this on {this.onChange} see the solution below

import React from 'react'


class UsernameForm extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        username: ''
    }
    this.onchange=this.onChange.bind(this)
    this.onSubmit=this.onSubmit.bind(this)
}

onChange(e) {
    this.setState({
        username: e.target.value
    })
}

onSubmit(e) {
    e.preventDefault()
    this.props.onSubmit(this.state.username)
}

render() {
    return (
        <div>
            <form onSubmit={this.onSubmit}>
                <input type='text'placeholder='What is your username ?' onChange={this.onChange.bind(this)} />
                <input type='submit' />
            </form>
        </div>
    )
}

}

export default UsernameForm

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far