[英]How to convert a string into JSX in React 17
Given some string:给定一些字符串:
const someString = "<p>Here is some string <strong>with some nested HTML</strong></p>"
I could remove the <p>
and </p>
from the string and then with React do:我可以从字符串中删除
<p>
和</p>
,然后使用 React 执行以下操作:
React.createElement('p', {
dangerouslySetInnerHTML: {
__html: html,
},
})
(We are assuming html
here is the string someString
with the removed p
tags) (我们假设
html
是删除p
标签的字符串someString
)
However, React 17 released with the new JSX Transform: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html然而,React 17 发布了新的 JSX 转换: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
Meaning React no longer compiles down to React.createElement
an instead directly compiles down to JSX.这意味着 React 不再编译为
React.createElement
而是直接编译为 JSX。
Is there a way to accomplish this with the new JSX Transform?有没有办法用新的 JSX 转换来完成这个?
In fact yes you can using JSX
syntax similar to React.createElement
事实上是的,你可以使用类似于
React.createElement
的JSX
语法
React.createElement('p', {
dangerouslySetInnerHTML: {
__html: html,
},
})
will become会变成
_jsx('p', {
dangerouslySetInnerHTML: {
__html: html,
},
})
You will however need to import: import { jsx as _jsx } from 'react/jsx-runtime';
但是,您需要导入:
import { jsx as _jsx } from 'react/jsx-runtime';
Note: My issues was Typescript was complaingin Could not find a declaration file for module 'react/jsx-runtime'.
注意:我的问题是 Typescript 是抱怨
Could not find a declaration file for module 'react/jsx-runtime'.
I needed to add // @ts-ignore
to ignore the JSX import我需要添加
// @ts-ignore
以忽略 JSX 导入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.