K
K
KirylLapouski2018-02-13 12:18:50
JavaScript
KirylLapouski, 2018-02-13 12:18:50

Why is the handler not hung on the react component?

There is such a component

var React = require('react');
class Task extends React.Component {

    constructor(props){
      super(props);

      this.state = {
        isOpened:false
      }
    }
    clickHandler(e){
      e.preventDefault();
      console.log('!!!');
      this.setState({
        isOpened: !this.state.isOpened
      });
      return false;
    }

    render(){
      var description = this.state.isOpened?this.props.description:'';

        return <a onClick={this.clickHandler.bind(this)} href="#" className="list-group-item list-group-item-action flex-column align-items-start">
        <div className="d-flex w-100 justify-content-between">
          <h5 className="mb-1">{this.props.name}</h5>
          <small>3 days ago</small>
        </div>
        <p className="mb-1">{description}</p>
      </a>
    }
}

module.exports = Task;

But when I rendered the handler element, I did not see it.
5a82ad24694b7711482051.png
What's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-02-13
@KirylLapouski

And where did you get the idea that he should be there? I think you should tighten up the basics of JavaScript .
If you are using ES6 syntax , use imports and exports: It is better to bind handlers not in render , but in the constructor:

constructor(props) {
  super(props);

  this.state = {
    isOpened: false,
  };

  this.clickHandler = this.clickHandler.bind(this);
}

Or define the handler as a class field arrow function :
clickHandler = e => {
  // your stuff
};

Such a function is bound to the instance context and does not need to be bound.
create-react-app supports this syntax out of the box.
You cannot pass the current state to the setState method , since this is an asynchronous method, by the time the call is made, the state may have changed and the old value will be used. To update the state based on the previous one, pass a function returning an object to setState . When called, the first argument to it will be the current state at the time of the update:
this.setState(prevState => ({
  isOpened: !prevState.isOpened,
}));

Instead of var , use const for immutable values ​​and let for mutable ones.
Finally, keep your code clean. Here are some good Airbnb guidelines :
Airbnb JavaScript
Guide Airbnb React Guide

K
KirylLapouski, 2018-02-23
@KirylLapouski

When rendering on the server, regular html comes to the client, which knows nothing about handlers. To fix this, you need to write a script tag to the page that you send, which contains the code for attaching components, as if it were being rendered on the client.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question