关于这个主题的许多类似的帖子都出现了,但是在我的应用程序的上下文中没有一个是有意义的,所以我发布这个,让我知道它是否重复并且它已经有了答案。
一个Circle
组件,使用div
事件处理程序呈现一个简单的onMouseMove
元素。调用UpdateCoords
函数,该函数在该元素上发送指针的位置,该元素存储为state
:
this.state = {
position: {x: null, y: y}
};
我有一个父组件Main
渲染Circle
组件,现在我想我需要使用state
组件中的Circle
的值,但我不太确定如何。
当您想要将数据从父级传递给子级时,您使用道具,并且当从子级到父级时使用回调函数。
主要部分
class Main extends React.Component {
constructor( props ) {
super(props);
this.state = {
position: { x: null, y: null}
};
}
updateCoords = (x , y) => {
this.setState({
position: {
x, y
}
});
}
render(){
return(
<div className='main-container'>
<Circle mouseMove={ this.updateCoords }/>
<pre>
<p> x - y: {this}</p>
</pre>
</div>
);
}
}
圆形组件
class Circle extends React.Component {
constructor(props){
super(props);
this.state = {
position: {x: null, y: null}
}
this.updateCoords = this.updateCoords.bind( this );
}
updateCoords( evt ){
let x = evt.clientX;
let y = evt.clientY;
this.setState({
position: {
x: x,
y: y,
}
});
this.props.mouseMove(x, y);
console.log("Clicked");
}
render() {
return(
<div className="circle" onMouseMove={ this.updateCoords }>
<span>
x: {this.state.position.x}, y: {this.state.position.y}
</span>
</div>
);
}
}