【问题标题】:Ways to dynamically generate JSX动态生成 JSX 的方法
【发布时间】:2021-01-15 21:48:29
【问题描述】:

我正在尝试向用户提供搜索建议,其中用户在搜索字段中输入的值在建议中突出显示。例如,如果我们有一个城市名称字符串数组,并且用户在输入中键入“new”,我会建议类似“New York City”。

我的原版 JS 解决方案:

const cities = [ 'New York City', 'Boston', 'Seattle', 'Miami' ];
const input = document.querySelector('input');
const searchValue = input.value;
const searchRegEx = new RegExp(searchValue, 'gi');
const filteredCities = cities.filter(city => city.match(searchRegEx));
const suggestions = filteredCities.map(city => city.replace(searchRegEx, '<span class="highlight">$&</span>')).join('');

// Insert suggestions into DOM here...

问题是我正在使用 React 并且 HTML 字符串被转义。我知道我可以使用 dangerouslySetInnerHTML 道具,但它似乎气馁。这是一个有效的用例还是有更好的方法?感谢您的帮助!

【问题讨论】:

  • 没有必要为此使用危险的SetInnerHTML。我正在投票重新开放。
  • 如果你在 React 中工作,那么最好看看一些 React 代码。也许this threadthis lib 会给你一些想法。
  • 也许使用服务器发送具有相关样式的结果(在您的情况下,也许您可​​以说 isBold),然后将样式动态应用于文本。真的不需要dangerouslySetInnerHTML
  • @NicholasTower 重复标志基于我对该问题的接受答案,该答案不使用dangerouslySetInnerHTML。值得一提的是,React 的 dangerouslySetInnerHTML 并不比在原生 JavaScript 中直接设置 el.innerHTML 更危险。只是 React 更明确地说明了危险。

标签: javascript reactjs jsx


【解决方案1】:

对此的反应方法将类似于以下内容:

const cities = [ 'New York City', 'Boston', 'Seattle', 'Miami' ];

const Example = () => {
  const [searchValue, setSearchValue] = useState('');
  const searchRegEx = new RegExp(searchValue, 'gi');
  const filteredCities = cities.filter(city => city.match(searchRegEx));

  return (
    <div>
      <input
        type="text" 
        value={searchValue} 
        onChange={e => setSearchValue(e.currentTarget.value)}
      />
      {filteredCities.map(city => {
        const match = city.match(searchRegexEx);
        const index = match.index;
        return (
          <React.Fragment>
            {city.slice(0, index)}
            <span class="highlight">{city.slice(index, index + searchValue.length)}</span>
            {city.slice(index + searchValue.length)}
          </React.Fragment>
        )
      })}
    </div>
  )
}

我可能在上面的代码中遇到了一些错误,因此您可能需要对其进行调整。但基本思想是:将字符串拆分为 3 个字符串,然后使用 JSX,将其中的第二个字符串渲染为包裹在 &lt;span&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多