【问题标题】:React-select: How to display HTML in optionsReact-select:如何在选项中显示 HTML
【发布时间】:2018-08-25 15:01:10
【问题描述】:

我想知道 react-select 是否可以在渲染选项中显示 html。例如,如果获取的 ajax 选项有 <b>text</b>,我希望在下拉菜单中看到粗体文本,而不是看到 <b>text</b>

我阅读了文档,但没有找到任何选项。

谢谢

【问题讨论】:

    标签: javascript reactjs select react-select


    【解决方案1】:

    我实现了上述解决方案,但它破坏了可搜索功能。标签需要一个字符串,而不是一个元素。 -- 实际上有一个 prop/function 可以做到这一点

    formatOptionLabel={function(data) {
      return (
        <span dangerouslySetInnerHTML={{ __html: data.label }} />
      );
    }}
    

    查看这篇文章:React-Select: How to maintain search-ability while passing HTML to the label value in options

    【讨论】:

      【解决方案2】:

      就这么简单:

      { value: 'foo', label: <span dangerouslySetInnerHTML={{ __html: 'bar &amp; foo' }} /> }
      

      没有选项组件,没有选项渲染器,只有简单的jsx。

      【讨论】:

      • 感谢您提供简单的解决方案!然而,这似乎打破了isSearchable,你有解决办法吗?
      【解决方案3】:

      你可以依赖 react-select 的 optionComponent prop 和 React 的 dangerouslySetInnerHTML feature 并给optionComponent一个这样的组件

      const MyOptionComponent = props => <span dangerouslySetInnerHTML={{__html : props.option}} />;
      

      【讨论】:

      • 嗯我不明白这应该如何工作;。 props.dangerouslySetInnerHTML 必须采用 {__html: ...} 的形式,而且我已经在使用 optionRenderer 作为荧光笔,例如此处的示例:github.com/JedWatson/react-select/issues/5
      • 这样使用它:dangerouslySetInnerHTML={{ __html: finalHtml }}
      【解决方案4】:

      您可以为react-select 创建自定义optionRendereroptionComponent

      我推荐你optionRenderer,因为它更简单,如果你只想把转换成html。您可以在此处查看示例:

      https://github.com/jquintozamora/react-taxonomypicker/blob/master/app/src/components/TaxonomyPicker/TaxonomyPicker.tsx#L135-L148

      这里还有另一个optionComponent 示例(以防万一您需要额外的功能): https://github.com/JedWatson/react-select/blob/master/examples/src/components/CustomComponents.js#L15

      【讨论】:

      • 您好,您的示例只是更改了选项的呈现方式,仍然存在未解释 html 的问题。我已经将自定义 optionRenderer 用于荧光笔,如下所述:github.com/JedWatson/react-select/issues/5
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多