【问题标题】:Handling Show More/Less text in React Native在 React Native 中处理显示更多/更少文本
【发布时间】:2020-08-09 17:28:48
【问题描述】:

我收到来自远程 API 的 HTML 格式的响应。除非您按 Read More 按钮,否则不应显示整个内容 响应如下所示:

"<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 上建议的解决方案,该解决方案涉及添加自定义渲染器,该渲染器将所有 &lt;p&gt; 标签替换为 react native &lt;Text&gt; 标签,该标签具有我需要的 numberOfLines 道具:

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

它有效,但问题是我的description 变量中有几个&lt;p&gt; 标签,它显示所有标签都缩短到我输入的行数,而不是缩短整篇文章。所以我想我必须使用一个唯一的标签来包装整个 HTML 内容,然后应用相同的逻辑

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

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

经过几次 Google 搜索后,偶然发现了一个名为 react-native-read-more-text 的第三方库 我知道它只适用于&lt;Text&gt; 标签内的内容,所以我再次使用模板字符串由&lt;Text&gt; 包装

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

这次我收到错误:

如果有任何帮助,我将不胜感激

【问题讨论】:

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


    【解决方案1】:

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

    • 将您的 HTML 内容包装在一个高度约为 5 行的容器中;
    • 此容器在其底部具有淡化效果(在 Goodreads 等用户评论平台中很常见);
    • 在此容器的底部,可以按下“阅读更多”按钮来扩展容器高度以适应 html 内容高度。

    如果你需要一个标签渲染器来实现这样的特性,你应该看看这个 SO 帖子:https://stackoverflow.com/a/69200348/2779871

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-12
      • 2020-06-18
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2020-02-15
      • 1970-01-01
      相关资源
      最近更新 更多