简体   繁体   English

使用Typescript的React Router的“ React”未定义

[英]“React” undefined for React Router with Typescript

This is my React Router setup that I want to run through Typescript. 这是我要通过Typescript运行的React Router设置。 It works without Typescript, but not with it. 它在没有Typescript的情况下有效,但不能与之兼容。 I get an runtime error in my browser console. 我在浏览器控制台中收到运行时错误。 Transpilation works fine though. 编译工作正常。 It doesn't make a difference if I include a “react.js” and “react-dom.js” seperately or a giant “bundle.js” with everything included. 如果我分别包含“ react.js”和“ react-dom.js”,或者包含所有内容的巨型“ bundle.js”,则没有什么区别。 What am I doing wrong? 我究竟做错了什么?

Error: 错误:

Router.js:91 Uncaught TypeError: Cannot read property 'Component' of undefined
// For context, the line says: React.Component
at Object../node_modules/react-router/es/Router.js (Router.js:91)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/react-router-dom/es/Router.js (Router.js:2)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/react-router-dom/es/BrowserRouter.js (BrowserRouter.js:11)
at __webpack_require__ (bootstrap:19)
at Object../node_modules/react-router-dom/es/index.js (index.js:1)
at __webpack_require__ (bootstrap:19)
at Object../src/index.tsx (index.tsx:3)
at __webpack_require__ (bootstrap:19)

Code: 码:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch }  from "react-router-dom";

class App extends React.Component {
  render() {
    return (
        <Router>
        <Switch>
        <Route path="/test/" render={() => (
            <div>
                Test.
            </div>
        )} />
        <Route exact={true} path="/" render={() => (
            <div>
                Root page.
            </div>
        )} />
        </Switch>
        </Router>
    );
  }
}

ReactDOM.render(
    <App />,
    document.getElementById("root") as HTMLElement
);

Okay. 好的。

The solution was to add "esModuleInterop": true to my tsconfig.json . 解决方案是在我的tsconfig.json添加"esModuleInterop": true

Additionally, "allowSyntheticDefaultImports": true allowed me to write import React from "react"; 另外, "allowSyntheticDefaultImports": true允许我import React from "react";编写import React from "react"; instead of import * as React from "react"; 而不是import * as React from "react"; .

Thanks everyone. 感谢大家。

The way you import React is the problem. 问题是导入React的方式。 You should replace all your importing statements with something like this: 您应该使用以下内容替换所有导入语句:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM