gpt4 book ai didi

react-native - 如何在 native react 中从父 View 组件向所有子组件添加填充/边距?

转载 作者:行者123 更新时间:2023-12-01 21:42:12 25 4
gpt4 key购买 nike

我想为我的所有子组件(Icon)添加相同的填充/边距,只是将样式放入 View 组件中。我怎样才能实现?

<View style={{flexDirection: "row",}}>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
</View>

最佳答案

父级实际上可以修改其子级。看看下面的包装器组件:

const Wrapper = ({ childStyle, children, ...viewProps }) => (
<View {...viewProps}>
{React.Children.map((children, child) =>
React.cloneElement(child, {
style: [child.props.style, childStyle],
}),
)}
</View>
);

// This will add margin to all your stars:
<Wrapper style={{flexDirection: "row",}} childStyle={{margin: 8}}>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
</View>

这使用 React.Children.map 迭代给定 Wrapper 的子项,然后使用 React.cloneElement 转换它们并注入(inject)我们从父级传递的样式。

关于react-native - 如何在 native react 中从父 View 组件向所有子组件添加填充/边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61227336/

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