我正在努力在 React 的组件之间传递引用。我决定使用 React.forwardRef 但出现问题。这是我的代码
const Wrapper = React.forwardRef((props, ref) => {
return (
<StyledWrapper ref={ref} >
{console.log(ref.current)}
<ParallaxProvider scrollContainer={ref.current}>
<TransitionProvider value={ref.current}>{children}</TransitionProvider>
</ParallaxProvider>
</StyledWrapper>
);
});
export default class MainTemplate extends React.Component {
constructor(props) {
super(props);
this.scrollContainer = React.createRef();
}
render() {
const { toggled, overflow } = this.state;
const { uri, children } = this.props;
return (
<>
<SEO />
<GlobalStyle />
<ThemeProvider theme={GlobalTheme}>
<>
<Hamburger handleToggle={this.handleToggle} />
<Perspective active={toggled}>
<Navigation pathname={uri} handleToggle={this.handleToggle} />
<Wrapper
ref={this.scrollContainer}
>
{children}
</Wrapper> …Run Code Online (Sandbox Code Playgroud) 当页面初始滚动不在加载时的顶部时,我正在努力解决滚动视差问题。我使用react-scroll-parallax库(https://www.npmjs.com/package/react-scroll-parallax)。为了解决我的问题,我尝试使用他们的建议https://www.npmjs.com/package/react-scroll-parallax#example-usage-of-context。
import { useEffect } from 'react';
import { useController } from 'react-scroll-parallax';
const ParallaxCache = () => {
const { parallaxController } = useController();
useEffect(() => {
const handler = () => {
parallaxController.update();
console.log(1);
};
window.addEventListener('load', handler);
return () => document.removeEventListener('load', handler);
}, [parallaxController]);
return null;
};
export default ParallaxCache;
Run Code Online (Sandbox Code Playgroud)
我将 ParallaxCache 组件放在我的应用程序顶部(实际上是页面,因为它是 gatsby)。
但“加载”事件似乎不起作用。我也尝试过“DOMContentLoaded”,但结果相同。然而,其他事件(例如“滚动”或“调整大小”)可以正常工作,并且我的控制器会更新。我是否遗漏了某些内容或反应阻止使用此事件?