簡體   English   中英

如何在React.js中獲取另一個組件的元素?

[英]How can I get the element of another component in React.js?

我有兩個組件CarouselComponent和BannerComponent嵌套到App Component。 我想在CarouselComponent的BannerComponent中獲取滾動功能的元素。

代碼在這里;

--- App.js

....
<App>
   <BannerComponent />
   <CarouselComponent />
</App>
....

--- BannerComponent.js

...
return(
<div className="banner-div" id="banner-div">
</div>
);
...

--- CarouselComponent.js

...
scrollTo() {
  document.getElementById("banner-div") //  This doesn't work
}
...

return(
<a onClick={this.scrollTo}></a>
); 

我想知道如何在所有情況下獲得反應中的元素。

forwardRef是你需要在這里實現的。

  • 首先,在BannerComponent組件中設置ref。
  • 其次,在您的App組件中轉發ref。
  • 第三,在CarouselComponent組件中獲取轉發的ref。

或者,如果你仍然想使用dom,那么我可以想到這樣做的可能方法:

內部App組件:

state = {
  domMounted: false //initial state
}

componentDidMount() {
  this.setState({domMounted: true})
}

這將確保您安裝了完整的App組件,現在您可以訪問子組件中的dom元素:

首先,傳遞像didMount={this.state.domMounted}這樣的道具

<CarouselComponent didMount={this.state.domMounted}>

CarouselComponent組件:

const {didMount} = this.props
if(didMount) { // this will run on every render and finally get true
  document.getElementById("banner-div")
}

現在,你的onClick處理程序將不會獲得null元素,事件將正常工作。

React ref將在這里工作。

class SomeComp extends React.Component{

constructor(){
    this.carRef = React.createRef(); //create ref
}
  render(){
    return(
      <div>
        <App>
          <BannerComponent  carRef={this.carRef}/> //pass ref in Banner Component to attach it to required DOM.
          <CarouselComponent carRef={this.carRef}/> //pass ref to CarouselComponent  to use it
        </App>
      </div>
    )
  }
}

BannerComponent

class BannerComponent extends React.Component{

  render(){
    return(
      <div className="banner-div" id="banner-div"  ref={this.props.carRef}>
      </div>
    );
  }   
}

CarouselComponent

class CarouselComponent extends React.Component{

  scrollTo() {
    this.props.carRef.current.scrollTo(50)
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM