Why doesn't the ref attribute?

Why doesn't the ref attribute. I want to move this block on the screen, not triggered ref

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( 
the <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;
June 8th 19 at 17:12
2 answers
June 8th 19 at 17:14
Solution
You have the wrong handler.
First, rename from Mousedown to handleClick.
In JavaS—Āript not called methods with a capital letter, and chandlery called format handleSomeEvent or someEventHandler.

Second either use the class field function:
handleClick => e {
console.log(this.ourDiv);
};


either wrap the handler in an anonymous function when passing in the onClick:
<div style="{this.state.move}" onclick="{()" => this.handleClick()}
 ref={ourDiv => this.ourDiv = ourDiv}
></div>


The problem is that class method when you transfer to another location loses its context and this no longer points to your object.
Yes, I understand, I forgot the bind to do. Damn, what is that one small line, and I sit like an idiot half an hour - Harrison_McLaughl commented on June 8th 19 at 17:17
June 8th 19 at 17:16
Solution
When you call MouseDown this will be equal to undefined. More can be read here.

To avoid this proizoshlo, you can use arrow functions (best option):

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


Either in the designer to write:

constructor(props){
super(props);
//...
 this.onClick = this.onClick.bind(this);
}


The worst option is to wrap the function in a pointer, because it will be created on each call to render:

this.onClick()}/>

Find more questions by tags React