我试图在用户滚动页面时更改标题的颜色样式,但是,我的onScroll
方法似乎甚至无法触发。有人可以告诉我为什么以及如何解决这个问题?正在底部onScroll
组件上调用TemplateWrapper
方法。此外,如果您对如何以不同方式做任何其他建议,我全都耳朵!谢谢!
const headerStyle = {
background: 'grey',
marginBottom: '1.45rem',
position: 'fixed',
top: 0,
left: 0,
width: '100%',
zIndex: '99'
}
const modHeader = () => {
headerStyle.background = 'white'
console.log('scroll')
}
const Header = () => (
<div className='header'
style={headerStyle}
>
<div
style={{
margin: '0 auto',
maxWidth: 1160,
padding: '1.45rem 1.0875rem',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between'
}}
>
<h1 style={{ margin: 0 }}>
<Link
to="/"
style={{
color: 'white',
textDecoration: 'none',
}}
>
Gatsby
</Link>
</h1>
<h2 style={{ margin: 0 }}>
<Link
to="/about"
style={{
color: 'white',
textDecoration: 'none',
}}
>
About
</Link>
</h2>
</div>
</div>
)
const TemplateWrapper = ({
children
}) => (
<div onScroll={modHeader}>
<Helmet
title="Gatsby Default Starter"
meta={[
{ name: 'description', content: 'Sample' },
{ name: 'keywords', content: 'sample, something' },
]}
/>
<Header />
<div
style={{
margin: '0 auto',
maxWidth: 960,
padding: '0px 1.0875rem 1.45rem',
paddingTop: 0,
}}
>
{children()}
</div>
</div>
)
export default TemplateWrapper
答案 0 :(得分:2)
您需要添加一个eventlistener componentDidMount并将您的值存储在状态中,您需要在onScroll上重新呈现组件,
componentDidMount = () => {
window.addEventListener('scroll', ()=>{
this.setState({
// your flags
});
});
};
注意:如果你想为你的div添加事件监听器,你可以通过参考这样的反应来访问它,
componentDidMount = () => {
this.listener.addEventListener('scroll', ()=>{
this.setState({
// your flags
});
});
};
render(){
return(
<div ref={(listener) => { this.listener = listener }}></div>
)
}