[英]React - How do you get the top position of a styled component?
當您不了解React方式時,以前很簡單的事情會變得相當復雜。
我正在嘗試創建一個組件,使其在到達頁面頂部時充當粘性頁眉或頁腳。
目前我很滿足於添加以下內容:
componentDidMount() {
window.addEventListener('scroll', this.onScroll, false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll, false);
}
但是,我在如何獲得樣式化組件的滾動頂部位置方面遇到了瓶頸。 假設我有一個名為Container
的樣式化組件,它輸出了一個表單,我通常只添加一個數據屬性並執行如下操作:
const container = document.getElementbyTag("data-sticky-container")
const position = container.offsetTop
我將如何在 React 中執行此操作?
現在使用ref
。 我遇到了一個沒有定義 current 的問題:
constructor(props) {
super(props);
this.optionBox = React.createRef();
}
componentDidMount() {
window.addEventListener('scroll', this.onScroll, false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll, false);
}
onScroll() {
console.log(this.optionBox.current.offsetTop);
}
在反應中,您將為您的組件使用參考: https ://reactjs.org/docs/refs-and-the-dom.html
你會有這樣的事情:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
getOffset = () => {
console.log(this.myRef.current.offsetTop);
}
render() {
return <Container ref={this.myRef} onClick={this.getOffset} />;
}
}
現在你可以通過this.myRef.current.offsetTop
在你的onScroll
函數中訪問容器 offsetTop,就像在getOffset
中一樣
另一種選擇是使用 innerRef。 這可能會更好,因為它將為您提供對 DOM 節點的引用,而不僅僅是一個包裝器。 看到這個答案。
然后,您可以更直接地訪問scrollTop
等屬性。
與ref
不同, innerRef
使用回調:
在您的情況下,它看起來像:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef;
}
getOffset = () => {
console.log(this.myRef.offsetTop);
}
render() {
return <Container
innerRef={element => this.textInput = element}
onClick={this.getOffset} />;
}
}
您可以將ref添加到您想要 offsetTop 的組件。 此 ref 將包含該組件的所有計算 css 值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.