gpt4 book ai didi

javascript - react : Mapping children of a parent component

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:08 24 4
gpt4 key购买 nike

因此,我想向附加到组件的任何子项添加某些样式。在这种情况下,假设父组件称为 Section,子组件称为 Card。在 Section.js 我正在尝试这个:-

renderChildren = () =>{
return React.Children.map(this.props.children, (child, i)=>{
let el = React.cloneElement(child,{
style: {opacity:0.5}
})
return el
})
}

render(){
<ScrollView>
{this.renderChildren()}
</ScrollView>
}

上述方法对我不起作用。我想知道为什么。还有一种方法可以让我映射到子节点并将它们包装在一个新组件中吗?像这样的东西;

this.props.children.map(Child => <Wrapper> <Child/> </Wrapper> )

最佳答案

要将您的 child 包装到包装器中,只需调用电话 React.Children.map进入包装器组件:

const OpaqueWrapper = ({ children }) => (
// check that children is defined
// if you do not want your wrapper to be rendered empty
children && (
<Wrapper>
{React.Children.map(children, child => (
React.cloneElement(child, {style: {...child.props.style, opacity: 0.5}})
))}
</Wrapper>
)
);

另请注意,您必须将提供给原始子项的样式与注入(inject)的样式合并,否则您将完全失去为子项设置样式的能力。

See this codesandbox一个工作示例。

至于为什么它在您的代码中不起作用:Are you sure that your <Card>组件确实处理 style正确地支持,即将它应用到它的 child ?

编辑:

The sloution wraps all children components in a single wrapper, but I would like to wrap each child with the applied wrapper , as shown in my question.

只需将包装器移入 React.Children.map :

const OpaqueWrapper = ({ children }) => (        
React.Children.map(children, child => (
<Wrapper>
{React.cloneElement(child, {style: {...child.props.style, opacity: 0.5}})}
</Wrapper>
)))
);

关于javascript - react : Mapping children of a parent component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49496906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com