如何根据文本内部的文本调整本机文本组件的大小?

时间:2018-05-21 10:56:15

标签: react-native

我有两个文本组件彼此相邻。

第一个应该扩展,只要内部文本需要,并且当它将第二个压缩超过一行时切换到省略号。

e.g。

Short text - 1 Alert                             |

Really really really long text is s... - 1 Alert |

栏位于可用空间的末尾。

目前发生的情况是,无论alertProfile组件中的文本是什么,它总是占用相同百分比的屏幕,因此我得到一个带有短文本的大量空白区域。同时,长文本被过早截断,因此我在警报后最终会使用未使用的空格。

e.g。

Short text              - 1 Alert                |

Really really really... - 1 Alert                |

我的问题是如何让长文本尽可能多地使用空格,以及尽可能少地使用短文本。

代码示例如下。

export function Heading(props) {
  const { title, number } = props;
  let alertCountText = " - 1 Alert";
  if (number !== 1) {
    alertCountText = ` - ${number} Alerts`;
  }
  return (
    <View style={expandedStyle.header}>
      <Text numberOfLines={1} style={[expandedStyle.alertTitle]}>
        {title}
      </Text>
      <Text style={[expandedStyle.alertCount]}>
        {alertCountText}
      </Text>
    </View>
  );
}

const expandedStyle = StyleSheet.create({
  header: {
    flex: 1,
    flexDirection: "row",
    justifyContent: "flex-start",
    alignItems: "center"
  },
  alertTitle: {
    flex: 1,
    fontFamily: "Lato-Bold",
    fontSize: 16,
    fontWeight: "bold",
    fontStyle: "normal",
    lineHeight: 18
  },
  alertCount: {
    flex: 1,
    fontFamily: "Lato-Regular",
    fontSize: 14,
    fontWeight: "normal",
    fontStyle: "normal",
    lineHeight: 14
  }
});

1 个答案:

答案 0 :(得分:2)

检查一下。我对react-native不太确定。但是这个可以根据你的要求与flexbox完美配合,所以我猜这将是一个有价值的答案。

.wrapper {
  display: inline-flex;
  width: 70%;
  border: 1px solid #ddd;
  margin-bottom: 10px;
}
.text {
  display: inline-block;
  white-space: nowrap; 
  max-width: calc(100% - 100px);
  overflow: hidden;
  text-overflow: ellipsis; 
}
.alert {
  margin-left: 5px;
}
<div class='wrapper'>
  <span class='text'>Text</span>
  <span class='alert'>Alert</span>
</div>

<div class='wrapper'>
  <span class='text'>Long Text</span>
  <span class='alert'>Alert</span>
</div>

<div class='wrapper'>
  <span class='text'>Really Really Really Really Long Text</span>
  <span class='alert'>Alert</span>
</div>

相关问题