【问题标题】:Cannot change width and height of custom component in React-native?无法在 React-native 中更改自定义组件的宽度和高度?
【发布时间】:2018-05-01 21:18:36
【问题描述】:

我有一个最小的自定义无状态组件,如下所示:

const ViewBox = (props) => (
    <View style={ mainStyle : {backgroundColor: 'beige'} }>
        {props.children}
    </View>
)
export default ViewBox;

所以我想在另一个组件中导入并使用它。

export default class Test extends React.Component {

render() {
    return (
        <View style={styles.containerView} >
            <ViewBox style={styles.mainBox}>
              <Text style={[styles.boxTitle, {color: '#8F468C'}]}>Lorem ipsum...</Text>
            </ViewBox>
        </View>
    );
    }
}

const styles = {    
  containerView: {
    flex: 1,
    marginTop: 50,
    alignItems: 'center',
    backgroundColor: 'brown',
  },
  mainBox: {
    flex: 1,
    width: 250,  //No effect ! ! !
    height: 250  //No effect ! ! !
  },
  boxTitle: {
    backgroundColor: 'pink',
    fontSize: 17,
    marginTop: 20
  }
};

这里我们至少有 2 个莫名其妙的事实:
1) 更重要的是,ViewBox(或您要在此处使用的每个 自定义 组件)的宽度和高度完全失控!分配数字大小或 Flex 值无效,ViewBox 保持呈现内部文本所需的最小宽度/高度。

2)删除根视图(因此 ViewBox 成为根) ViewBox 继续忽略任何大小,但现在它填满了所有可用空间......为什么???

所有提到的行为都是使用自定义视图(在本例中为 ViewBox)发生的,如果将其替换为普通视图,则所有操作都按预期工作。
我想知道足够多的 React-native 的 flex 和 UI 最佳实践,但是文档没有很好地涵盖这两种情况。希望有人能给我惊喜!

【问题讨论】:

  • 那么你到底想达到什么目的呢?

标签: react-native flexbox components react-native-flexbox


【解决方案1】:

这实际上是 flexbox 的工作原理:

  1. Flex 容器默认带有flexShrink: 1,这意味着它们将缩小到其内容。添加flexShrink: 0 会改变这一点。您可能需要使用 minWidthminHeight 来代替。

  2. 它伸展的原因是因为没有什么可以告诉它的。您的容器的默认 alignItems: 'stretch'alignItems: 'center' 覆盖,这会缩小其内容。

查看 Snack 上的示例代码:https://snack.expo.io/B1VdUma1M

有一个非常棒的 flexbox 备忘单/playground 显示了以下行为:https://yoksel.github.io/flex-cheatsheet/

记住React Native's implementation is slightly different

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
  • 2020-08-08
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多