1

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} ref={(ourDiv)=> this.ourDiv = ourDiv} onClick ={this.MouseDown}></div>
				</div>
			</div>
			)

	}
}



export default Main;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

1 ответ 1

1

Попробуйте так:

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

или просто забиндить вашу функцию MouseDown:

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

Почему у вас не получалось вызвать ref можете прочитать тут: https://reactjs.org/docs/handling-events.html

1
  • Точно забыл bind сделать
    – Sinevik
    31 янв 2018 в 15:35

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.