[英]passing props to children missing props
如何将道具传递给孩子们?
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,但是上面的代码给了我未定义的内容?
您不需要在这里进行销毁。 像这样接受props
const Tabs = ( props ) => {
// ... props.children - is your children object
}
如果您想使用解构,那就是这样
const Tabs = ( {children, activeTab } ) => {
// now children and activeTab is passed props
}
无论activeTab
和children
将被传递到你的组件作为属性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 })
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.