我正在尝试将变量'styles'传递给style = {styles}。我该怎么做呢?
function Header() {
var prevScrollpos = window.pageYOffset;
var currentScrollpos = window.pageYOffset
window.onscroll = function () {
if (prevScrollpos > currentScrollpos){
var styles = {
top: '0'
}
} else {
var styles = {
top: '-100px'
}
}
}
return (
<div className = 'navbar' style = {styles}>
<div id = 'mainButtons' >
<button id = 'projects'> PROJECTS </button>
<button id = 'about'> ABOUT </button>
<button id = 'contact'> CONTACT </button>
<button id = 'resume'> RESUME </button>
</div>
</div>
)
答案 0 :(得分:3)
由于您正在使用功能组件,因此可以尝试使用React Hooks并将其存储为组件State Hook的一部分。请注意,React挂钩仅添加在React 16.8上。
function Header() {
const [headerStyle, setHeaderStyle] = useState({
top: '0',
});
window.onscroll = function () {
if (prevScrollpos > currentScrollpos){
setHeaderStyle({
top: '0',
});
} else {
setHeaderStyle({
top: '-100px',
});
}
}
return (
<div className = 'navbar' style = {styles}>
<div id = 'mainButtons' >
<button id = 'projects'> PROJECTS </button>
<button id = 'about'> ABOUT </button>
<button id = 'contact'> CONTACT </button>
<button id = 'resume'> RESUME </button>
</div>
</div>
)
}
答案 1 :(得分:1)
如果您不想使用状态(如果可以将某些内容作为道具传递,则不应该使用状态)
function Header() {
const styles = {};
const updateStyle = top => {
styles.top = top;
};
window.onscroll = function() {
if (prevScrollpos > currentScrollpos) {
updateStyle(0);
} else {
updateStyle(-100);
}
};
return (
<div className="navbar" style={styles}>
<div id="mainButtons">
<button id="projects"> PROJECTS </button>
<button id="about"> ABOUT </button>
<button id="contact"> CONTACT </button>
<button id="resume"> RESUME </button>
</div>
</div>
);
}