假设我有这样的布局:
<Container>
<Name>
{name}
</Name>
<City>
{city}
</City>
</Container>
这里预期的输出是要与左边对齐的名称和城市。我想要另一个组件,其中这两个组件将集中对齐。我知道我可以直接在Name和City上使用textAlign='center'
,但我想要的是在父容器中设置该属性,因为如果我有10个嵌套元素并且所有这些元素应该集中对齐,我宁愿不要为所有组件编写相同的样式属性。
理想情况下,我会有类似的东西:
<Container textAlignChildren='center'>
...
</Container>
答案 0 :(得分:0)
您应该使用React.Children.map
对子项进行迭代,并使用React.cloneElement
返回每个子项的克隆。此方法将创建一个新元素,并在第二个参数合并时传递props。
class Container extends Component {
constructor() {
this.renderChildren = this.renderChildren.bind(this);
}
renderChildren() {
const { children, textAlignChildren } = this.props;
// Iterate over children and return clones
return React.Children.map(children, child => {
//return cloned child with merged style
return React.cloneElement(child, {
style: { textAlign: textAlignChildren }
});
});
}
render() {
return (
<div>
{this.renderChildren}
</div>
);
}
}
您将按以下方式调用
<Container textAlignChildren="center">
<Child />
<Child />
<Child />
</Container>
答案 1 :(得分:0)
您应该使用Flexbox在React Native中设置用户界面的样式。
如果你想一个接一个地显示一系列组件,&#34;在每一行&#34; (例如,使用文本),垂直集中,您应该将父容器的 alignItems 属性设置为值&#39; center&#39; 。
实施例
<View style={{ flex: 1, alignItems: 'center' }}>
<Text>Some Child</Text>
<Text>Some Child</Text>
<Text>Some Child</Text>
<Text>Some Child</Text>
</View>
注意:默认情况下,React Native中的主轴垂直向下移动,因此flexDirection
为'column'
,除非指定为不同的值。我强烈建议你看看this reference for Flexbox。 React Native的official documentation也很有帮助。