我需要使用getBoundingClientRect()
來獲取組件完全呈現後特定元素的確切位置。生命週期方法一旦呈現組件
我需要使用哪種生命週期方法?渲染完成後我不認爲componentDidMount()
被調用。我的組件呈現DIV
元素的列表。可能有多達30-40個。一旦它們被渲染,我想自動滾動到一個特定的元素。該元素可以位於渲染部分的底部,中間或任何位置。我爲每個DIV
元素標識,因此很容易告訴getBoundingClientReact()
給我它的位置。一旦我得到這些數據,我將滾動到該位置。
UPDATE:
這是我的代碼如下所示:
componentDidUpdate(prevProps, prevState) {
// Get the ID of the element I need to scroll to
const id = "divId-" + prevProps.myId;
// Find the rendered element
const element = document.getElementById(id);
// Get coordinates
const position = element.getBoundingClientRect();
// Call scrollTo custom function to scroll to the element
scrollTo(position.top);
// Set the new location
this.props.actions.setLocation(position.top);
}
是的,'setLocation'基本上在Redux存儲區中設置新的位置。一旦我明白了,設置新位置的最佳方式是什麼?基本上,我找出'componentDidUpdate()'中的新位置作爲我的代碼的一部分。 – Sam
>請注意,您不能在這裏調用this.setState();你也不應該做其他任何事情(比如派遣一個redux動作),在componentWillUpdate返回之前觸發一個React組件的更新。如果您需要更新狀態以響應道具更改,請使用componentWillReceiveProps()。 – HyeonJunOh
我希望這可以幫助你。 – HyeonJunOh