我想为我的所有子组件(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>
Run Code Online (Sandbox Code Playgroud)
实际上,父级可以修改其子级。看一下以下包装器组件:
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>
Run Code Online (Sandbox Code Playgroud)
这用于React.Children.map迭代给定的子级Wrapper,然后React.cloneElement转换它们并注入我们从父级传递的样式。
| 归档时间: |
|
| 查看次数: |
5610 次 |
| 最近记录: |