将道具传递给儿童失踪的道具

时间:2018-04-18 15:27:33

标签: javascript reactjs

如何将道具传递给儿童?

const Tabs = ({ children, props }) => {
  console.log(props) //where is activeTab??
  return React.Children.map(children, child =>
    React.cloneElement(child, { ...props })
  )
}

const App = () => {
  return (
    <Tabs activeTab={1}>
      <div>tabs children</div>
    </Tabs>
  );
};

期望道具是一个对象,其中activeTab等于1,但上面的代码给了我未定义的内容?

https://codesandbox.io/s/vnz4z84vq7

2 个答案:

答案 0 :(得分:1)

你不需要在这里进行解构。只需接受props作为参数,就像这样

const Tabs = ( props ) => {
// ... props.children - is your children object
}

如果你想使用解构,那就像这样

const Tabs = ( {children, activeTab } ) => {
// now children and activeTab is passed props
}

答案 1 :(得分:1)

activeTabchildren都将作为props参数的属性传递给您的组件,因此要访问它们,只需将您的组件更改为:

const Tabs = (props) => {
  console.log(props.activeTab);
  console.log(props.children);
  return React.Children.map(children, child =>
    React.cloneElement(child, { ...props })
  )
}

或者如果你想解构,你可以写

const Tabs = ({ children, activeTab, ...props }) => { 
   console.log(activeTab);
   console.log(children);
   return React.Children.map(children, child =>
     React.cloneElement(child, { ...props })
   )
}