我需要使用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