[英]How re-calculate the window container/image width on resize?
我在React中有一個方法/函數,其中單擊時使用CSS的轉換值左右滑動。 但是,在渲染時將加載屏幕,屏幕將向左或向右移動,並且轉換值將正確設置。 但是問題是,當我嘗試調整瀏覽器大小時,計算無法正常進行。
我嘗試創建一個onClick = {this.ResizeSlider},然后從那里運行該功能,但是不起作用。
我的代碼:
NextSlide = () => {
const {
currentIndex,
data
} = this.state;
const slideWidth = this.slideWidth();
// Exiting the method early if we are at the end of the images array.
// We also want to reset currentIndex and translateValue, so we return
// to the first image in the array.
if(currentIndex === data.length - 1) {
return this.setState({
currentIndex: 0,
translateValue: 0
})
}
// This will not run if we met the if condition above
this.setState(NextState => ({
currentIndex: NextState.currentIndex + 1,
translateValue: NextState.translateValue + -(slideWidth)
}));
}
slideWidth = () => {
const { slideClass } = this.state;
return document.querySelector(slideClass).clientWidth
}
您需要添加一個eventListener,以便您知道屏幕大小已更改的時間。
嘗試這樣的事情:
componentDidMount() {
this.dimensionsChange();
window.addEventListener("resize", this.dimensionsChange());
}
您可以使用以下方法在DimensionsChange()方法中訪問寬度/高度值:
var w = window.innerWidth;
var h = window.innerHeight;
卸載組件時,請不要忘記刪除事件偵聽器:
componentWillUnmount() {
window.removeEventListener("resize", this.dimensionsChange());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.