[英]Sending state data down to parent component
關於此主題的很多類似的帖子都出現了,但是在我的應用程序上下文中,它們都沒有意義,因此我將其發布,讓我知道它是否重復並且已經有了答案。
Circle
組件使用onMouseMove
事件處理程序呈現一個簡單的div
元素。 調用UpdateCoords
函數,該函數發送指針在存儲為state
元素上的位置:
this.state = {
position: {x: null, y: y}
};
我有一個父組件Main
,它呈現了Circle
組件,現在我想我需要使用Circle
組件的state
值,但是我不太確定如何使用。
當您想將數據從父級傳遞到子級時,可以使用props,而當從子級傳遞到父級時,可以使用回調函數。
主要成分
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> ); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.