【问题标题】:Inserting html inside string variable used in React component在 React 组件中使用的字符串变量中插入 html
【发布时间】:2018-06-13 12:39:28
【问题描述】:

我正在为我的投资组合网站构建一个 React 应用程序。目前我的应用程序是用 JSX 编写的,所以我可以添加如下内容:

class Project extends React.Component {
render() {
    return (
        <div className={this.props.project.class}>
            <h1>{this.props.project.header}</h1>
            <div>
                <div className='description'>
                    <p>{this.props.project.description}</p>
                    <p>The Tech Stack</p>
                    <ul>
                        {
                        this.props.project.items.map(function(listValue){
                            return <li>{listValue}</li>;
                        })}
                    </ul>
                </div>
                <div className='image'>

                </div>
            </div>

        </div>
    );
}

}

到我的组件。我目前正在另一个名为 Text.js 的文件中管理我的长文本字符串:

export let exampleText = "Graded is a application developed by <a href='google.com'> Link here. </a> and myself for our second year user interfaces course.";

并在我的 jsx 文件中访问它:

var gradedItems = {
    class: "gradedSection content",
    header: "Graded",
    description: Text.exampleText,
    items : ["Java", "Android"]
}

然后它会显示在上述组件的&lt;p&gt; 标记中。然而,正如我所提到的,链接实际上并没有呈现,html 标签也没有被呈现。所以它看起来像一些文本,然后是网站中的标签。

我应该如何在这个字符串中添加这些 html 标签,以便当组件渲染它时,里面的 html 元素会被渲染出来?

在这种情况下是否有可能,有没有更好的方法来做我想要实现的目标?

一如既往的感谢!

【问题讨论】:

  • 还有一个包可以避免dangerouslySetgithub.com/utatti/react-render-html,还有一些其他的包做同样的事情。
  • 是的,render-html 是最简单的解决方案。谢谢@Dave

标签: javascript html reactjs jsx


【解决方案1】:

您只需要使用dangerouslySetInnerHTML,它就会有所帮助。

示例用法:

let exampleText = "Graded is a application developed by <a href='google.com'> Link here. </a> and myself for our second year user interfaces course.";
function Component() {
  return <div dangerouslySetInnerHTML={{__html: exampleText }} />;
}

【讨论】:

    【解决方案2】:

    一种选择是将Text.js 中的字符串更改为 html 位,例如

    export const exampleText = (
      <span>
        Graded is a application developed by 
        <a href='google.com'> Link here. </a>
        and myself for our second year user interfaces course.
      </span>
    );
    

    【讨论】:

      【解决方案3】:

      首先你npm install html-react-parser

      import Parser from 'html-react-parser';
      
      var exampleText = 'Graded is a application developed by <a href='google.com'>     Link here. </a> and myself for our second year user interfaces course.';
      
      
      render: function() {
          return (
              <div>{Parser(exampleText)}</div>
          );
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-02
        • 1970-01-01
        • 2019-04-14
        • 1970-01-01
        • 2020-04-02
        • 2016-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多