Javascript 在reactJS中将类组件转换为函数组件
我想在react中制作parralax效果 我找到了一个教程,解释了如何 我的代码是用Functional组件编写的,但在示例中它是类组件 下面是一个例子Javascript 在reactJS中将类组件转换为函数组件,javascript,reactjs,react-functional-component,Javascript,Reactjs,React Functional Component,我想在react中制作parralax效果 我找到了一个教程,解释了如何 我的代码是用Functional组件编写的,但在示例中它是类组件 下面是一个例子 class Header extends React.Component { constructor() { super() this.state = { offset: 0 }; } return ( <header className='header-background'
class Header extends React.Component {
constructor() {
super()
this.state = {
offset: 0
};
}
return (
<header
className='header-background'
style={{ backgroundPositionY: this.state.offset}}
>
<section
className='info-container'
style={{ bottom: this.state.offset / 2 }}
>
<h1>Kevin Simpson</h1>
<h3>Front End Developer</h3>
</section>
</header>
)
}
componentDidMount() {
window.addEventListener('scroll', this.parallaxShift);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.parallaxShift);
}
parallaxShift = () => {
this.setState({
offset: window.pageYOffset
});
};
类头扩展React.Component{
构造函数(){
超级()
此.state={
偏移量:0
};
}
返回(
凯文·辛普森
前端显影剂
)
}
componentDidMount(){
window.addEventListener('scroll',this.parallaxShift);
}
组件将卸载(){
window.removeEventListener('scroll',this.parallaxShift);
}
视差偏移=()=>{
这是我的国家({
偏移量:window.pageYOffset
});
};
我用我的知识把它变成了功能性的
const [offset, setOffset] = useState(0);
useEffect(() => {
window.addEventListener('scroll', setOffset(window.pageYOffset));
});
return (
...
<svg style={{ bottom: offset }} className="border-circle" width={107} height={107} viewBox="0 0 107 107" >
....
const[offset,setOffset]=useState(0);
useffect(()=>{
window.addEventListener('scroll',setOffset(window.pageYOffset));
});
返回(
...
....
实际上,当我滚动时,没有触发任何
setOffset
,事件侦听器没有触发事件。我发现您的代码有三个问题
像这样编写useEffect应该可以工作谢谢你的帮助,但我不知道当我动态更新html元素时,它们会比其他叠加的html元素高,没有动画它就在下面