简体   繁体   中英

React.createElement throws Component not defined

I'm currently playing around with ReactJS using TypeScript as the underlying language wher I define my components.

I saw on many sites, that it is possible to render such components within a page (in my case cshtml ). Especially here which I tried to accomplish. To do so there should be something like:

<!-- ... -->
<body>
    <div id="myTargetId"></div>
</body>
<!-- ... -->

<script src="@(Url.Content("~/Scripts/React/dist/commons.js"))"></script>
<script src="@(Url.Content("~/Scripts/React/dist/MyComponent.js"))"></script>
<script>
    ReactDOM.render(React.createElement(MyComponent, {}), document.getElementById("targetId"));
</script>

Currently I get the following error:

Uncaught ReferenceError: MyComponent is not defined

This is what my MyComponent.tsx looks like:

import * as React from "react";

export interface IMyComponentProps { }
export interface IMyComponentState { }

export class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
    render(): JSX.Element {
        return (
            <p>This comes from ReactJs</p>
        );
    }
}

To pack this all together I am using webpack with the following webpack.config.js (simplified):

const webpack = require("webpack");
module.exports = {
    entry: {
        MyComponent: "./Scripts/React/Modules/MyComponent.tsx"
    },
    output: {
        path: path.join(__dirname, "./Scripts/React/dist/"),
        filename: "[name].js"
    },

    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

And, finally, this is the emitted JavaScript :

webpackJsonp([0],[
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const React = __webpack_require__(1);
class MyComponent extends React.Component {
    render() {
        return (React.createElement("p", null, "This comes from ReactJs"));
    }
}
exports.MyComponent = MyComponent;


/***/ }),
/* 1 */
/***/ (function(module, exports) {

module.exports = React;

/***/ })
],[0]);
//# sourceMappingURL=MyComponent.js.map

What am I missing here?

Uncaught ReferenceError: MyComponent is not defined

Your import is wrong:

<script src="@(Url.Content("~/Scripts/React/dist/commons.js"))"></script>
<script src="@(Url.Content("~/Scripts/React/dist/MyComponent.js"))"></script>

You should be building a bundle.js using webpack.

More

One of many quickstarts on the internet https://basarat.gitbooks.io/typescript/docs/quick/browser.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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