我正在尝试对句子中的某些词应用跨度。
return "hello how are you hello".replace(/hello|you/gi, <span className="some-class">"new"</span>);
在我看来,我看到的是 [object Object] 而不是 (span)new(span) (span)new(span) (span)new(span)
我也尝试过使用 dangerouslySetInnerHTML 但没有成功。我仍然得到 [object Object]
最佳答案
String.prototype.replace
返回一个字符串,因此它将您的 React.createElement
调用转换为字符串 [object Object]
。
相反,您可能希望将句子拆分成单词,映射它们并返回 jsx(如果它与您的正则表达式匹配),否则返回字符串。
var stringArray = "hello how are you hello".split(" ")
var regex = /hello|you/i
var elements = stringArray.map(string =>
regex.test(string) ? <span>{ string }</span> : string
)
render() {
return <div>{ elements }</div>
}
关于javascript - 在 react 中对字符串应用跨度会返回 [object Object] 而不是给我跨度文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463637/