我有一个需要参数化的字符串,例如“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 转义某些东西有关,但说实话,这完全是猜测。我有什么想法可以实现所需的功能吗?
最佳答案
您可以尝试替换为包含原始 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/