在React Native中处理显示更多/更少文本

时间:2020-04-26 07:25:54

标签: html reactjs react-native react-redux react-native-render-html

我从HTML格式的远程API得到响应。除非您按 阅读更多 按钮,否则不应显示全部内容 响应如下所示:

"<p>A suspension concentrate (SC) formulation containing 450 g/litre of napropamide (41.4% w/w) for the control of annual grass and broad-leaved weeds in winter oilseed rape.</p>\r\n<p><strong>DIRECTIONS FOR USE</strong><br /> IMPORTANT: This information is approved as part of the product label. All instructions within this section must be read carefully in order to obtain safe and successful use of this product.</p>\r\n<p><strong>RESTRICTION/WARNINGS</strong><br /> Weed control may be reduced where the spray is mixed too deeply into the soil. <br />Do not treat crops adversely affected by poor soil, adverse weather or cultural conditions. <br />Avoid spray overlap, particularly on headlands. <br />It is important to ensure that the seedbed is free from clods and weeds, and in good tilth.<br /> Incorporation under wet conditions is not satisfactory. <br />AC650 can be used on a wide range of soils but should not be applied to Sands (ADAS &rsquo;85 system)
...

我使用react-native-render-html库进行渲染,不幸的是,该库没有numberOfLines道具。

我尝试了在Github上建议的解决方案,该解决方案包括添加自定义渲染器,以用本机<p>标签替换所有<Text>标签,该标签具有我需要的numberOfLines道具:

<HTML
   html={`<p>${description}</p>`}
   renderers={{p: (_, children) => <Text numberOfLines={5}>{children}</Text>}}
/>

它起作用了,但问题是我的<p>变量中有几个description标签,它显示所有标签都缩短到我输入的行数,而不是缩短了整篇文章。因此,我认为必须使用唯一的标签来包装整个HTML内容,然后应用相同的逻辑

<HTML
  html={`<section>${description}</section>`}
  renderers={{section: (_, children) => <Text>{children}</Text>}}
/>

同样,该解决方案有效,但它弄乱了内部内容。没有应用换行符,等等。

再经过几次Google搜索后,偶然发现了名为react-native-read-more-text的第三方库 我了解它仅适用于<Text>标记内的内容,因此我再次使用模板字符串

<Text>包装
<ReadMore
  numberOfLines={10}
  renderTruncatedFooter={renderTruncatedFooter}
  renderRevealedFooter={renderRevealedFooter}>
    <HTML
    html={`<Text>${description}</Text>`}
    />
</ReadMore>

这次我收到一个错误:

enter image description here

我将不胜感激

1 个答案:

答案 0 :(得分:0)

我的建议是不要弄乱react-native-render-html,而是执行以下操作:

  • 将HTML内容包装在高度约5行的容器中;
  • 此容器的底部会逐渐褪色(通常在诸如Goodreads这样的用户查看平台中);
  • 在此容器的底部,可以按下“阅读更多”按钮以扩展容器的高度以适合html内容的高度。