如何根据子视图的高度设置父视图的高度

如何根据子视图的高度设置父视图的高度

本文介绍了如何根据子视图的高度设置父视图的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个自定义的父 View,其中包括一个 Text 组件子视图或两个 Text 组件子视图.有没有办法根据 Text 视图的高度设置父 View 的高度?

I want to write a customized parent View which includes either one Text componet subView or two Text component subViews. Is there a way to set the parent View's height based on the Text view's height?

class ParentView extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const {
      titleText,
      bodyText,
    } = this.props;

    //if titleText is passed to props, measure it's height;
    //if bodyText is passed to props, measure it's height;
    // set contentContainer height = titleText + bodyText + someMargin
    return (
      <View style={styles.contentContainer}>
        {titleText && <Text style={styles.title}>
          {titleText}
        </Text>}
        {bodyText && <Text style={styles.body}>
          {bodyText}
        </Text>}
      </View>
    );
  }
}

推荐答案

您可以在 View 容器上设置 flex:0

You can set flex:0 on your View container

const styles = StyleSheet.create({
  contentContainer: {
    flex: 0
  }
});

通过这种方式,它会根据孩子的身高进行扩展.

with this way it will expand according to the children height.

关于 flex 属性的一些信息:

A few info about flex property:

当 flex 为正数时,它使组件变得灵活并且它将与它的 flex 值成正比.所以一个带有 flex 的组件设置为 2 将占用两倍于 flex 设置为 1 的组件的空间.

flex 为 0 时,组件根据宽高调整大小而且不灵活.

When flex is 0, the component is sized according to width and height and it is inflexible.

当 flex 为 -1 时,组件通常根据宽度和高度.但是,如果没有足够的空间,组件将缩小到它的 minWidth 和 minHeight.

When flex is -1, the component is normally sized according width and height. However, if there's not enough space, the component will shrink to its minWidth and minHeight.

这篇关于如何根据子视图的高度设置父视图的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:33