我正在努力在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>
</Perspective>
</>
</ThemeProvider>
</>
);
}
}
我需要将ref.current传递给and问题是ref.current始终为null。谁能向我解释这种行为,我如何使它起作用?
在React引用中始终分配在第一个渲染之后。在第一个渲染之前尝试访问将提供一个空对象。
解决此问题的一种方法是使用条件渲染
const Wrapper = React.forwardRef((props, ref) => {
return (
<StyledWrapper ref={ref} >
{ref.current &&
<ParallaxProvider scrollContainer={ref.current}>
<TransitionProvider value={ref.current}>{children}</TransitionProvider>
</ParallaxProvider>
}
</StyledWrapper>
);
});
此外,如果您编写了ParallaxProvider
和TransitionProvider
组件,则可以将它们修改为在它们不为空时分别仅使用scrollContainer
和value
...
值得指出的是,React不会在ref更改时重新渲染,但是由于它是作为prop传递给Wrapper
的,因此prop的更改将导致rerender,并且您应该能够获得ref.current
。