javascript - 在 React 中渲染字符串内的 HTML 实体

标签 javascript html reactjs html-entities

我在 React JS 中显示大引号 HTML 实体时遇到问题。引用straight and curly quotes

    render() {
      return (
              <h4>
              {theme == 'blue' && 'This is sample text'}
              {theme == 'red' && 'What&rsquo;s your role in this project'}
              </h4>
            )
         }

电流输出

What&rsquo;s your role in this project

预期输出
您在这个项目中扮演什么 Angular 色

我不想使用危险的SetInnerHTML,或者我不想在 react 状态属性中定义这些值。提前致谢。

最佳答案

使用String.fromCharCode方法:

检查 React 文档:https://shripadk.github.io/react/docs/jsx-gotchas.html

MDN 文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode

查找字符代码:http://www.mauvecloud.net/charsets/CharCodeFinder.html

render() {
          return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && `What ${String.fromCharCode(8217}s your role in this project`}
                  </h4>
                )
             }

文本的模板文字``

render() {
          return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && `What’s your role in this project`}
                  </h4>
                )
             }

使用双引号和单引号

render() {
          return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && "What’s your role in this project"}
                  </h4>
                )
             }

使用转义字符

 return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && 'What \’s your role in this project'}
                  </h4>
                )
             } 

关于javascript - 在 React 中渲染字符串内的 HTML 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63240955/

相关文章:

javascript - HTML Canvas & JavaScript - 选择菜单 - 设置初始和保持当前选择

javascript - 滚动时使 div 高度增大和缩小(React)

javascript - HTML 输入具有自动完成功能,但没有默认值

javascript - 如何在ajax中插入数组?

javascript - 我有清除输入文本宽度 jQuery 的问题

javascript - React Native 中组件之间的通信(子 -> 父)

javascript - react - 删除仅测试 Prop

reactjs - 开 Jest ,意外的 token 导入

javascript - Angular 4 中的多个指令

html - 无法在带有文本的缩略图上添加边框