我试图将变量“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>
)
最佳答案
由于您正在使用功能组件,因此您可以尝试使用 React Hooks并将其存储为组件的 State Hook 的一部分。请注意,react hooks 仅在 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>
)
}
关于javascript - 将变量从一个函数传递到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58869259/