如何在本机反应中从父视图组件向所有子组件添加填充/边距?

Md.*_*lah 2 react-native

我想为我的所有子组件(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)

Mar*_*sik 6

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

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转换它们并注入我们从父级传递的样式。