如何在TypeScript中将JSX存储到普通变量中?
在TypeScript的.ts文件中存储JSX到变量的解决方案
方案1:配置TypeScript并使用正确类型标注
如果需要在.ts文件里直接写JSX,先确保tsconfig.json的关键配置正确:
{ "compilerOptions": { "jsx": "react-jsx", // React 17+推荐用这个,旧版本可设为"react" "lib": ["dom", "es2015"], "types": ["react"] }, "include": ["src/**/*.ts"] }
然后给变量标注React.ReactNode或JSX.Element类型(无需用any):
import React from 'react'; const name = 'Keval'; const Ele: React.ReactNode = <div>Hello {name}</div>; export default Ele;
注:部分TypeScript版本可能对.ts文件中的JSX语法仍有报错,若无法修改文件扩展名,可换用方案2。
方案2:用React.createElement替代JSX语法
直接调用React.createElement创建元素,避免在.ts文件中写JSX语法,类型会自动推断正确:
import React from 'react'; const name = 'Keval'; const Ele = React.createElement('div', null, `Hello ${name}`); export default Ele;
必要依赖检查
确保已安装React类型声明包,否则TypeScript无法识别相关类型:
npm install @types/react --save-dev
内容的提问来源于stack exchange,提问作者Keval Mistry
相关产品推荐
相关产品推荐

