[英]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.