在不导入React的情况下使JSX工作

时间:2016-12-03 17:30:30

标签: reactjs

我正在尝试运行我的第一个React JSX文件,它可以工作!但是,我的JSX中没有包含这两个import语句:

import React from 'react';
import ReactDOM from 'react-dom';

我认为我需要这两个导入,以便在JSX被转换为JS(由React.createElement)时,React组件将在范围内。但即使没有两种进口,它似乎也能起作用。

如果没有导入,这是如何工作的?

这是我的代码:

script.jsx:

var Main = React.createClass({
    getIntialState: function () {
        return {
            counter: 0
        };
    },
    clickHandler: function () {
        return {
            counter: this.state.counter + 1
        };
    },
    render: function () {
        return (
            <button onClick={this.clickHandler}>+2</button>
        )
    }
});

package.json

{
  "name": "reactjs",
  "version": "1.0.0",
  "description": "",
  "main": "react.js",
  "dependencies": {
    "webpack": "^1.13.3"
  },
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.8",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "react": "^15.4.1",
    "react-dom": "^15.4.1"
  },
  "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "dev": "webpack --watch",
   "build": "webpack -p"
  },
  "author": "",
  "license": "ISC"
}

HTML文件

<html>
<head>

    <title>
        !My first React JS Component!
    </title>
</head>
<body>
    <div id="root"></div>
    <script src="react.js"></script>
    <script src="output.js"></script>
</body>
</html>

webpack.config.js

module.exports = {
    entry: "./app/script.jsx",
    output: {
        filename: "output.js"
    },
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                loader: 'babel-loader'
            }
        ]
    }
}

1 个答案:

答案 0 :(得分:4)

这是因为我在我的脚本标签中包含了react.js,正如@DorWeid指出的那样。所以即使没有导入它也能工作。谢谢大家,抱歉愚蠢!