React Native自动调整listItem的字体大小

时间:2018-12-06 17:17:48

标签: react-native dynamic font-size listitem

Example of text not fitting 您好,如图所示,您看不到全文,但是我不想减小所有其他项目的字体大小。

仅当长度大于16时。

我可以在我的renderTitleStyle方法中返回fontSize吗,还是可以在ListItem道具中使用,例如{infoText.length > 16 ? (fontSize: 12) : (fontSize: 32)},但是我认为这不起作用。

  renderTitleStyle = item => {
const infoText = item.location_from + item.location_to;
if (infoText.length > 12) {
  // Return fontSize ???
}
console.warn(infoText.length);
};


        <ListItem
      style={styles.activeUser}
      onPress={() => this.toggleModalConfirmTrip(item)}
      roundAvatar
      subtitle={item.user[0].name}
      titleStyle={this.renderTitleStyle(item)}
      title={`${item.location_from} to ${item.location_to} `}
      ....[![Example of text not fitting][1]][1]

1 个答案:

答案 0 :(得分:0)

通过传递带有取决于状态或条件的样式数组元素的样式数组,您应该能够动态设置样式。

<Text style={[styles.mainStyles, {fontSize: ((infoText && infoText.length) > 16 ? 12 :32) }]}>
   {/*other elements*/}
</Text>

在您的特定情况下,我将尝试将该条件作为属性传递给ListItem组件。

titleStyle={this._renderItemTitleStyle(item)}

不要忘记创建函数。

_renderItemTitleStyle = (item) => {
  if (item && Object.keys(item).length) {
    const infoText = item.location_from + item.location_to;
    return {fontSize: (infoText.length > 16 ? 12 :32)}
  }
  console.warn("param item has no properties");
}
相关问题