React平滑滚动仅部分生效:函数组件ref问题求助
Hey, I've run into this exact issue before with react-scrollable-anchor and functional components! The error you're seeing happens because stateless functional components (SFCs) don't have instances that refs can attach to by default, and react-scrollable-anchor relies on refs to target the correct scroll position. Here's how to fix it:
Solution 1: Wrap Functional Components with React.forwardRef
This lets you pass a ref from the ScrollableAnchor down to a DOM element inside your functional component, which gives the anchor a valid target to scroll to.
Example for your Resume component:
Original functional component:
const Resume = () => { return ( <div className="resume-section"> {/* Your resume content here */} </div> ); };
Updated with forwardRef:
const Resume = React.forwardRef((props, ref) => { return ( // Attach the passed ref to the root DOM element of your component <div ref={ref} className="resume-section"> {/* Your resume content here */} </div> ); });
Repeat this exact pattern for your Contact component—make sure to attach the ref parameter to the root DOM element of the component.
Then use your wrapped components in ScrollableAnchor like you did with your class components:
<ScrollableAnchor id={'resume'}> <Resume /> </ScrollableAnchor> <ScrollableAnchor id={'contact'}> <Contact /> </ScrollableAnchor>
Solution 2: Quick Fix - Wrap Components in a DOM Element
If you don't want to modify your functional components, you can wrap them in a plain block element (like a <div>) directly inside the ScrollableAnchor. This lets the anchor target the div instead of your functional component, avoiding the ref error entirely:
<ScrollableAnchor id={'resume'}> <div> <Resume /> </div> </ScrollableAnchor> <ScrollableAnchor id={'contact'}> <div> <Contact /> </div> </ScrollableAnchor>
Which to choose?
- Use the
forwardRefapproach if you want your components to be reusable with refs in other contexts. - Use the wrapper div for a fast, no-fuss fix that gets scrolling working immediately.
Either method should resolve the ref warning and get your resume/contact sections scrolling smoothly!
内容的提问来源于stack exchange,提问作者Emily Pancake

