javascript - 使用 React JS 在所有段落中添加 SPAN 元素

标签 javascript html reactjs dom

谁能帮我解决这个问题吗?

我有一个 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/

相关文章:

javascript - 版本 2.0.1 的速度滚动问题

javascript - AngularJS : How to execute function in pre-defined order?

javascript - 到达 DIV 容器末尾后换行

javascript - 如何使用 React Hooks 捕获最后一个输入字母

javascript - react 路由器: Cannot GET with email address as params

html - 如何在文本更改时保持图像的位置?

javascript - Redux:如何将 action creators 编译成一个 action creators 表?

javascript - 与 Node 异步不是更好吗

javascript - JS : window. 滚动(x,y)指向另一个框架在 Chrome 中不起作用

html - 如何显示 :hover color in gmail