谁能帮我解决这个问题吗?
我有一个 HTML 文档,里面有一堆段落元素,我想在其开头放置一个元素。内容是由用户创建的,例如使用所见即所得编辑器。
例如:
<p>Some text was written here</p>
<p>and here</p>
<p>and here</p>
应该变成:
<p><span></span>Some text was written here</p>
<p><span></span>and here</p>
<p><span></span>and here</p>
既然我无法直接修改 DOM,有没有办法用 ReactJS 来做这样的事情?
最佳答案
首先假设保存该段落的 prop 是 content
。
在渲染内容之前,您需要解析它并将其更改为String
,为此,请将此方法添加到您的组件
AddLeadingSpan( content ){
// pattern for the openeing P tag
const targetEl = /<p>/gi;
// substitute for the matching result
const subsEl = "<p><span>im a span tag </span>"; // add some text for relevance
// simply use the native string API to do the replacement
return content.replace( targetEl, subsEl);
}
不应直接从渲染函数调用上述方法,因为它返回一个字符串
,该字符串将被打印为字符串
。
为了解决这个问题,我们需要另一种方法(在本例中将充当中间件):
renderAsHTML( content ){
return(
{__html:this.AddLeadingSpan( content ) }
)
}
最后放开渲染方法:
render(){
return(
<div dangerouslySetInnerHTML={this.renderAsHTML( this.props.content )}>
</div>
)
}
您需要调用dangerouslySetInnerHTML
以React方式执行操作,有关更多信息,请检查dangerouslySetInnerHTML ,但您需要清理内容以防止 cross-site scripting (XSS)
关于javascript - 使用 React JS 在所有段落中添加 SPAN 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51913541/