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

React Native adjusting font size of listItem dynamically

嗨,如图所示,您看不到全文,但是我不想减少所有其他项目的字体大小。

只有当它们的长度大于 16 时。

我可以 return 我的 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]

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

<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");
}