Answer the question
In order to leave comments, you need to log in
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
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);
};
<div
style={this.state.move}
onClick ={() => this.handleClick()}
ref={ourDiv => this.ourDiv = ourDiv}
></div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question