[英]passing props to children missing props
How to pass props down to children? 如何将道具传递给孩子们?
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>
);
};
expecting props is an object where is has activeTab equal to 1 but above code gave me undefined? 期望道具是一个对象,其activeTab等于1,但是上面的代码给了我未定义的内容?
https://codesandbox.io/s/vnz4z84vq7 https://codesandbox.io/s/vnz4z84vq7
You dont need destructuring here. 您不需要在这里进行销毁。 Just accept
props
as argument like this 像这样接受
props
const Tabs = ( props ) => {
// ... props.children - is your children object
}
If you want to use destructuring it would be like this 如果您想使用解构,那就是这样
const Tabs = ( {children, activeTab } ) => {
// now children and activeTab is passed props
}
Both activeTab
and children
will be passed to your component as properties of props
parameter, so to access them just change your component to: 无论
activeTab
和children
将被传递到你的组件作为属性props
参数,所以访问它们只是改变你的组件:
const Tabs = (props) => {
console.log(props.activeTab);
console.log(props.children);
return React.Children.map(children, child =>
React.cloneElement(child, { ...props })
)
}
or if you want to destructure you can write 或者如果您想破坏结构,可以写
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.