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

React中如何正确向子组件传递props?props丢失问题求解

解决React Tabs组件props传递问题

嘿,我帮你定位到问题啦!你的Tabs组件参数解构方式写错了,导致拿不到activeTab属性。

问题原因

你当前的Tabs组件定义是:

const Tabs = ({ children, props }) => { ... }

这里你误以为props是一个独立的参数,但实际上React组件的第一个参数本身就是完整的props对象,children只是这个对象里的一个属性。你这样写相当于从props里解构出children和一个名为props的属性——但你并没有给Tabs传递props这个属性,所以它自然是undefined。

修复方案

有两种简单的修复方式:

方式1:使用剩余参数收集非children属性

const Tabs = ({ children, ...props }) => {
  console.log(props) // 现在能看到{ activeTab: 1 }啦
  return React.Children.map(children, child => React.cloneElement(child, { ...props }) )
}
const App = () => {
  return (
    <Tabs activeTab={1}>
      <div>tabs children</div>
    </Tabs>
  );
};

这里的...props会把除了children之外的所有传入属性(比如activeTab)收集到props对象里,这样就能正确拿到你需要的属性了。

方式2:直接接收完整的props对象

如果你不想解构,也可以直接接收整个props对象,再从中取出children:

const Tabs = (props) => {
  const { children } = props;
  console.log(props) // 这里的props包含activeTab和children
  return React.Children.map(children, child => React.cloneElement(child, { ...props }) )
}

这两种方式都能解决你的问题,选哪种看你个人的代码风格偏好~

内容的提问来源于stack exchange,提问作者Madeline Ries

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:45:22