S
S
sinevik2018-01-31 18:08:17
React
sinevik, 2018-01-31 18:08:17

Why doesn't the ref attribute work?

Why is the ref attribute not working? I want to move this block around the screen, ref does not work

import React from "react";



class Main extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      divStyle: {
        width:"1000px",
        height: "500px",
        outline: "1px solid red"
      },
      move: {
        width:"200px",
        height:"100px",
        outline: "1px solid green"

      }
    }

  }


    MouseDown(e){
                console.log(this.ourDiv);
    }

  

  render() {

    return(	
      <div>
        <div style={this.state.divStyle}>
          <div style={this.state.move}  onClick ={this.MouseDown} ref={(ourDiv)=> this.ourDiv = ourDiv}></div>
        </div>
      </div>
      )

  }
}



export default Main;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-01-31
@sinevik

Your handler is wrong.
First, rename from Mousedown to handleClick .
In JavaScript , it is customary to name methods with a capital letter, and it is customary to name handlers in the format handleSomeEvent or someEventHandler .
Second, either use the class field function :

handleClick => e {
  console.log(this.ourDiv);
};

or wrap the handler in an anonymous function when passed to onClick :
<div
  style={this.state.move}
  onClick ={() => this.handleClick()}
  ref={ourDiv => this.ourDiv = ourDiv}
></div>

The problem is that a class method loses its context when passed elsewhere, and this no longer points to your object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question