javascript - 将字符串中的大括号替换为 JSX 中的 HTML span 节点

标签 javascript string reactjs jsx

我有一个需要参数化的字符串,例如“Hello {name}, how are you?”。我想用变量替换里面的大括号和文本,然后在我的 React 组件中渲染它,但我还需要通过将变量文本包装在 span/strong 标签中来突出显示和粗体文本,例如期望的最终结果

Hello <span class="text-info"><strong>Dave</strong></span>, how are you?

我正在使用 React/JSX,并且我知道如何使用 String.replace 替换大括号和其中的文本,然后渲染它,例如

// This string with the placeholder curly braces would be received from an API call to a server. Only set here for demonstrative purposes
let string = 'Hello {name}, how are you?' 
let name = 'Dave' // Likewise would not be set manually here, it's held in a redux store
let greeting = string.replace(/{(.*?)}/, name);

// This renders the greeting as you'd expect e.g. <p>Hello Dave, how are you?</p>
return (
   <p>{greeting}</p>
)

但是,如果我尝试用 span 元素替换大括号,它会使用 [object Object] 而不是我的参数错误地渲染

// ...rest of stateless Component.jsx
let greeting = string.replace(/{(.*?)}/, <span>{name}</span>);

// This renders the HTML <p>Hello [object Object], how are you?</p>
return (
   <p>{greeting}</p>
)

我认为这一定与 React 转义某些东西有关,但说实话,这完全是猜测。我有什么想法可以实现所需的功能吗?

JSFiddle:https://jsfiddle.net/ExoticChimp1990/o69ymt7q/

最佳答案

您可以尝试替换为包含原始 html 标签的字符串,然后使用angerouslySetInnerHTML 渲染您的div。

var greeting = textToEnhance.replace(/{(.*?)}/, '<span>'+this.props.name+'</span>'); 

return <div dangerouslySetInnerHTML={{__html:greeting}}></div>;

关于javascript - 将字符串中的大括号替换为 JSX 中的 HTML span 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39172627/

相关文章:

Python - 使用前 2 个元素转换列

ruby - 如何在 Ruby 中匹配和迭代另一个字符串

javascript - 如何更新 React 状态中的单个属性(函数组件)

javascript - 如何以 redux-form 更改一个字段值基于另一个字段值?

reactjs - react-redux : "super calls are not permitted outside constructors or in nested functions inside constructors" 中的 typescript 错误

php - Javascript 函数接受 PHP 变量

javascript - Jquery/Javascript 中的变量作用域

javascript - 使用push方法将对象插入数组

javascript - 在javascript中动态创建嵌套数组

regex - R在data.frame中获取双/三重姓氏的首字母