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?
You dont need destructuring here. Just accept props
as argument like this
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:
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 })
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.