You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用forwardRef的子组件无法访问父组件传入Props的问题求助

Help with ForwardRef Props Issue in React

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

  • forwardRef doesn't block props: The first parameter passed to the forwardRef callback is still the full props object, just like a regular React component. forwardRef only adds the second ref parameter 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 log renderCount right 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:27:49