React中使用forwardRef的子组件无法访问父组件传入Props的问题求助
Hey there! Let's get this sorted out for you—this is a common gotcha when starting out with forwardRef, so don't worry, we'll fix it quickly.
Looking at your code, the main issues preventing your Child component from accessing the renderCountHandler prop are:
1. Your Child component isn't returning JSX
Right now, your Child component's function has JSX written inside it, but you aren't explicitly returning it. React components need to return JSX (or null/undefined) to render properly. Without that return statement, the component won't work as expected—this might even be why you're confused about props not coming through!
2. Incomplete prop access in your JSX
You had <div>{props.}</div> which cuts off mid-access, but even if that was complete, the missing return would block it from rendering anyway.
Fixed Code Example
Here's your code updated to work correctly:
import { useState, forwardRef } from 'react'; const Parent = () => { const [renderCount, setRenderCount] = useState(4); const renderCountHandler = () => { // Use functional update here to avoid closure issues with stale state setRenderCount(prevCount => prevCount + 1); }; return ( <div> <p>Current Count: {renderCount}</p> <Child renderCountHandler={renderCountHandler}/> </div> ); }; const Child = forwardRef((props, ref) => { // Now you can access props.renderCountHandler perfectly fine! console.log(props.renderCountHandler); // This will log the function to your console return ( <div> <button onClick={props.renderCountHandler}>Increment Count</button> </div> ); });
Key Notes
forwardRefdoesn't block props: The first parameter passed to theforwardRefcallback is still the full props object, just like a regular React component.forwardRefonly adds the secondrefparameter to let you pass refs down to the child's DOM element or inner component.- Always return JSX: Make sure your component function returns the JSX you want to render—this is a fundamental rule for React components.
- Functional state updates: I swapped your
setRenderCount(renderCount + 1)to use the functional update form. This helps avoid issues where the state value might be stale (like if you tried to logrenderCountright after updating it in the handler).
Give this a try, and your Child component should be able to access the renderCountHandler prop without any issues!
内容的提问来源于stack exchange,提问作者Zenixo

