作者:莪鈈稀罕rn | 来源:互联网 | 2022-12-06 17:59
当你不知道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
.我遇到了一个没有定义电流的问题:
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);
}
Laurenz Glüc..
7
在反应中,您将使用组件的参考: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 ;
}
}
现在,您可以通过函数this.myRef.current.offsetTop
内部访问容器offsetToponScroll
getOffset
1> Laurenz Glüc..:
在反应中,您将使用组件的参考: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 ;
}
}
现在,您可以通过函数this.myRef.current.offsetTop
内部访问容器offsetToponScroll
getOffset