将状态数据发送到父组件

问题描述 投票:0回答:1

关于这个主题的许多类似的帖子都出现了,但是在我的应用程序的上下文中没有一个是有意义的,所以我发布这个,让我知道它是否重复并且它已经有了答案。

一个Circle组件,使用div事件处理程序呈现一个简单的onMouseMove元素。调用UpdateCoords函数,该函数在该元素上发送指针的位置,该元素存储为state

this.state = {
    position: {x: null, y: y}
};

我有一个父组件Main渲染Circle组件,现在我想我需要使用state组件中的Circle的值,但我不太确定如何。

javascript reactjs react-dom
1个回答
1
投票

当您想要将数据从父级传递给子级时,您使用道具,并且当从子级到父级时使用回调函数。

主要部分

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> 
      );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.