【问题标题】:How to convert a string into JSX in React 17如何在 React 17 中将字符串转换为 JSX
【发布时间】:2021-02-15 17:11:38
【问题描述】:

给定一些字符串:

const someString = "<p>Here is some string <strong>with some nested HTML</strong></p>"

我可以从字符串中删除 &lt;p&gt;&lt;/p&gt;,然后使用 React 做:

React.createElement('p', {
  dangerouslySetInnerHTML: {
    __html: html,
  },
})

(我们假设html这里是字符串someString,去掉了p标签)

不过,React 17 发布时带有新的 JSX 转换:https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

意思是 React 不再编译成 React.createElement 而是直接编译成 JSX。

有没有办法通过新的 JSX 转换来实现这一点?

【问题讨论】:

  • "而是直接编译成 JSX" - 我不确定你的意思,转换仍然输出纯 JS,只是将 React.createElement('h1', null, 'Hello world') 更改为 @987654331 @ 并自动注入新的导入,而不是要求开发人员确保 React 在范围内。
  • 你是对的!!你可以在导入import { jsx as _jsx } from 'react/jsx-runtime'; 时将React.createElement 转换为_jsx 我只需要使用// @ts-ignore 来忽略来自react/jsx-runtime 的导入

标签: reactjs jsx


【解决方案1】:

实际上是的,您可以使用类似于React.createElementJSX 语法

React.createElement('p', {
  dangerouslySetInnerHTML: {
    __html: html,
  },
})

会变成

_jsx('p', {
  dangerouslySetInnerHTML: {
    __html: html,
  },
})

但是,您需要导入: import { jsx as _jsx } from 'react/jsx-runtime';

注意:我的问题是 Typescript 抱怨 Could not find a declaration file for module 'react/jsx-runtime'. 我需要添加 // @ts-ignore 以忽略 JSX 导入

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2021-08-24
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多