我正在尝试运行我的第一个React JSX文件,它的工作原理!但是,我的JSX中没有包含这两个import语句: import React from 'react';import ReactDOM from 'react-dom'; 我以为我需要这两个导入,以便当JSX被转换
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' } ] } }这是因为我在我的脚本标签中包含了react.js,正如@DorWeid指出的那样.所以即使没有导入它也能工作.谢谢大家,抱歉愚蠢!