如何将道具传递给儿童?
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,但上面的代码给了我未定义的内容?
答案 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)
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 })
)
}