TSConfig JSX:React JSX 与 React

2024-05-03

在将 Typescript 与 React 一起使用时,我们必须指定jsx in compilerOptions in tsconfig.json file.

It has preserve, react, react-native, react-jsx等作为允许值。

{
  "compilerOptions": {
    "jsx": "react-jsx" | "react" | "react-native" | "preserve"
  }
}

react and react-jsx主要用于网络 我想了解这两个选项之间的区别以及何时选择哪一个

react将 jsx 翻译为React.createElement()

react-jsx将 jsx 翻译为_jsx() and _jsxs()

还有什么区别_jsx() and _jsxs() ?


最好使用react-jsx,解释如下:


两者的区别

首先,请记住,此选项仅控制如何在 JavaScript 文件中发出 JSX 构造。这仅影响以 .tsx 文件开头的 JS 文件的输出。

所以,两者的区别只是JS文件的输出。

输出 JS 文件打字稿文档 https://www.typescriptlang.org/tsconfig#jsx:

默认:"react"

import React from 'react';
export const HelloWorld = () => React.createElement("h1", null, "Hello world");

React 17 变换:“反应-jsx”

import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
export const HelloWorld = () => _jsx("h1", { children: "Hello world" });

哪个更好?

正如它所写的那样反应文档 https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-different-in-the-new-transform,实际上,"react"option 只是将 JSX 转换为常规 javascript 的旧方法,并不完美:

  • 因为 JSX 被编译到 React.createElement 中,所以如果您使用 JSX,React 需要在范围内。
  • React.createElement 不允许进行一些性能改进和简化。

为了解决这些问题,React 17 引入了 React 包的新入口点,这些入口点仅供 Babel 和 TypeScript 等编译器使用。

当您使用时“反应-jsx”选项,您正在使用这个新的 React 17 编译。

因此,最好使用“反应-jsx” option.

_jsx() 和 _jsxs() 有什么区别?

没有什么区别。图片来自jsx 运行时 https://github.com/itsjavi/jsx-runtime/tree/main代码库如下:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TSConfig JSX:React JSX 与 React 的相关文章

随机推荐