在使用 Flexbox 布局 View 时,我遇到了几次边距问题。
我设法用一个小代码片段重现了这个问题:
这是一个自定义组件:
class MyView extends Component {
render() {
return (
<View style={
{
backgroundColor: 'green',
width: 50,
height: 50
}
}/>
);
}
}
这是我的使用方法:
<View style={{ flexDirection: 'column' }}>
<MyView />
<MyView style={{ marginTop: 12 }}/>
</View>
所以我期望看到 2 个绿色方 block 彼此重叠,间隔 12px(由于 marginTop)。相反,这是我所看到的:
两个方 block 相互接触。我不知道为什么不考虑 margin 。
我尝试使用检查器工具调试底部 View ,以下是显示的内容:
您实际上可以看到该图像上的边距(浅橙色)。知道为什么不考虑 margin 吗?
最佳答案
class MyView extends Component {
render() {
const { style } = this.props;
return (
<View style={
[style, {
backgroundColor: 'green',
width: 50,
height: 50
}]
}/>
);
}
}
MyView.propTypes = {
style: React.propTypes.shape({
marginTop: React.propTypes.number
})
}
MyView.defaultProps = {
style: {
marginTop: 0
}
}
您正在将 style
作为 prop
传递到 MyView
中。我添加了 propTypes
和 defaultProps
因为您只偶尔传递 style
属性。
来自 React 文档
All of the core components accept a prop named style.
由于您的组件不是核心组件,因此 style
无法按您预期的方式工作。
关于React-native:弹性布局中未考虑边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44363942/