[英]ref from React.forwardRef is null
I'm struggling with passing refs between components in React.我正在努力在 React 中的组件之间传递引用。 I've decided to use React.forwardRef but i occur a problem.我决定使用 React.forwardRef 但我遇到了一个问题。 Here is my code这是我的代码
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>
</>
);
}
}
I need to pass ref.current to and but the problem is that ref.current is always null.我需要将 ref.current 传递给 and 但问题是 ref.current 始终为空。 Can anybody explain me this behavior and how can i make it works?任何人都可以向我解释这种行为,我该如何使它起作用?
In React refs are always assigned after the first render .在 React 中,refs 总是在第一次渲染之后分配。 Trying to access before the first render will give a null object.在第一次渲染之前尝试访问将给出一个空对象。
One way to get around this is to use conditional rendering解决这个问题的一种方法是使用条件渲染
const Wrapper = React.forwardRef((props, ref) => {
return (
<StyledWrapper ref={ref} >
{ref.current &&
<ParallaxProvider scrollContainer={ref.current}>
<TransitionProvider value={ref.current}>{children}</TransitionProvider>
</ParallaxProvider>
}
</StyledWrapper>
);
});
Also if you wrote the ParallaxProvider
and TransitionProvider
components, you can modify them to only use scrollContainer
and value
respectively when they're not null...此外,如果您编写了ParallaxProvider
和TransitionProvider
组件,则可以将它们修改为仅在它们不为 null 时分别使用scrollContainer
和value
...
It's worth pointing out that React doesn't rerender on ref change but since this is being passed as a prop to Wrapper
, a change in the prop will cause a rerender and you should be able to get ref.current
.值得指出的是,React 不会在 ref 更改时重新渲染,但由于这是作为道具传递给Wrapper
,道具的更改将导致重新渲染,您应该能够获得ref.current
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.