我想像下面这样渲染 JSX:
<p>
Some text with a <span> match </span> in it
</p>
我的想法是这样准备数据:
var text = ["Some text with a", <span>match</span>, "in it"]
return <p> {text} </p>
但这会导致 React 跟踪缺少键的迭代子项时出现问题。
Each child in an array or iterator should have a unique "key" prop.
知道如何解决这个问题吗?
编辑:要了解它的使用方式,请查看以下函数 stub :
/**
* prepares string with JSX span tags to assist with highlighting of search result matches
* @param {string} name string to find the match within
* @param {string} matchString the search query string that we are highlighting against
*
* @returns {Array} an array containing characters and JSX for syntax highlighting
*/
export const matchHighlighting = (name, matchString) => {...}
我知道搜索查询和响应文本,并想向用户显示高亮显示——我基本上是尝试编写一个函数,在必要时用 span 标记插入字符串的内容,给我留下一个类似于我在顶部发布的示例。
这react issues thread有点突出问题;听起来很难,还没有真正找到好的解决方案?
最佳答案
要解决与键相关的问题,您需要在每个数组元素上放置key
属性。要做到这一点,而不是
<p> {text} </p>
我们需要遍历数组,就像这样 -
{text.map((el,index)=> {<p key={index}>{el}</p>})}
关于javascript - react 渲染字符串数组和 JSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52378428/