Нужно сделать "плавающий" div
с сообщением, без jQuery, чтобы при прокрутке ниже header'a это сообщение крепилось в верху экрана.
Без ref'ов, на хуках, с функциональными компонентами.
JS:
import React, { useState, useRef } from "react";
import "./styles.css";
import { observable, computed } from "mobx";
import { observer } from "mobx-react";
const Header = () => (
<div className="header">
<h1>Header</h1>
</div>
);
const Message = React.forwardRef((props, ref) => {
return (
<div ref={ref} className="message">
<h2>Message</h2>
</div>
);
});
const Space = () => <div className="space" />;
@observer
class App extends React.Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
@observable sticky = this.ref.current.getBoundingClientRect();
someMethod() {}
render() {
return (
<div className="App">
<Header />
<Message ref={this.ref} />
<button
onClick={() => {
console.log(this.sticky);
this.ref.current.style.display = "flex";
}}
>
add message
</button>
<button
onClick={() => {
console.log(this.sticky);
this.ref.current.style.display = "none";
}}
>
remove message
</button>
<Space />
//получается сделать через событие
<button
onClick={() => {
if (this.ref.current.getBoundingClientRect().top < 0) {
this.ref.current.classList.add("sticky");
}
}}
>
add sticky
</button>
</div>
);
}
}
export default App;
CSS:
* {
margin: 0;
padding: 0;
}
.App {
font-family: sans-serif;
text-align: center;
}
.header {
height: 100px;
background: blue;
display: flex;
justify-content: center;
align-items: center;
}
.space {
height: 500px;
}
.message {
display: none;
background: green;
height: 70px;
justify-content: center;
align-items: center;
}
.sticky {
width: 100%;
position: fixed;
top: 0;
}
Думал, что нужно взять координаты сообщения и когда верхние будут отрицательными добавлять CSS-класс с position: fixed
.