React-native:弹性布局中未考虑边距

标签 react-native flexbox

在使用 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)。相反,这是我所看到的:

nomargin

两个方 block 相互接触。我不知道为什么不考虑 margin 。

我尝试使用检查器工具调试底部 View ,以下是显示的内容:

nomargin-debug

您实际上可以看到该图像上的边距(浅橙色)。知道为什么不考虑 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 中。我添加了 propTypesdefaultProps 因为您只偶尔传递 style 属性。

来自 React 文档

All of the core components accept a prop named style.

由于您的组件不是核心组件,因此 style 无法按您预期的方式工作。

关于React-native:弹性布局中未考虑边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44363942/

相关文章:

react-native - 如何将 core-js 更新为 core-js@3 依赖项?

javascript - 尝试呈现 "loading"提示,但数据一旦准备好

css - 关于显示 :-webkit-box; -webkit-box-flex:1 的一些事情

javascript - ScrollView子元素获取偏移量

javascript - 是否可以在 createMaterialBottomTabNavigator 中使用 createMaterialTopTabNavigator 的滑动过渡?

html - 具有多列布局和移动 div 框排序的 flexbox

html - 如何使用 Flexbox 将一列中的两个框对齐,紧挨着一行?

html - 如何计算 flex child 的 100% 宽度?

css - 具有大量嵌套的 Flexbox 工具栏

javascript - 在 React Native 中生成多个 APK?