【问题标题】:problems with babel react preset and react-dombabel react preset 和 react-dom 的问题
【发布时间】:2016-05-13 02:17:53
【问题描述】:

我正在使用 webpack 和 babel 将我的 jsx 文件预处理为 javascript。我的配置如下:

Webpack.config.js

module.exports = {
    entry: "./react/main.jsx",
    output: {
        path: __dirname,
        filename: "./public/javascripts/app.js"
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['react', 'es2015']
                }
            }
        ]
    }
};

./react.main.jsx

import { render } from 'react-dom'
import HelloWorld from './components/helloworld.jsx'
render(<HelloWorld />,document.body);

./react/components/helloworld.jsx

import React from 'react'

class HelloWorld extends React.Component {
    static render() {
        return (
            <div>
                <h1>Hello World!</h1>
                <p>This is some text</p>
            </div>
        );
    }
}

export default HelloWorld;

当我运行 webpack 时,我在 app.js 的这一行中不断收到错误 React is not defined

(0, _reactDom.render)(React.createElement(_helloworld2.default, null), document.body);

如果我特别在我的 main.jsx 文件中包含 react 错误就会消失,然后错误是

Uncaught Invariant Violation: _registerComponent(...): Target container is not a DOM element.指向null值作为app.js中React.create element的第二个参数

我确定这是我遗漏或做错的事情,但我不知道是什么。

【问题讨论】:

  • 您是否在 node_modules 文件夹中安装了 react ? ( npm install -save 反应)
  • 您应该使用 document.getElementById('root') 例如并在您的 html 文件中包含
    。如果你这样做,你不应该有错误 Target container is not a DOM
  • 当然你还需要在你的main.jsx中导入Reactreact-dom 也使用 react

标签: javascript reactjs ecmascript-6 webpack babeljs


【解决方案1】:

将这行代码添加到您的 main.jsx 文件中。

import React from 'react'

作为react-dom 使用react,但主要原因是文件包含 JSX 并且 JSX 只是转换为 React.createElement 调用 - Felix Kling

来自升级指南 React v0.14

现在直接将 document.body 作为容器传递给 ReactDOM.render 发出警告,因为这样做可能会导致浏览器扩展出现问题 修改 DOM。

所以把你的标记改成

<body>
  <div id="app"></div>
</body>

之后你可以将你的组件渲染到div标签

render(<HelloWorld />,document.getElementById('app'));

谢谢

【讨论】:

  • 您可能想解释为什么需要这样做,以便其他人了解问题。
  • "as a react-dom uses react."这可能也是个问题,但主要原因是文件包含JSX,而JSX只是转换为React.createElement来电。
【解决方案2】:

感谢大家的帮助。我没有意识到react-dom 本身并不是require 'react'。无论如何,问题的另一半是 app.js 在编译后的位置。我把它放在身体之后的底部,一切都很完美。我确实收到了关于 document.body 的警告,所以我将其更改为使用 div。

【讨论】:

  • 由于 ReactDOM,您不必导入 React。您必须导入 React,因为您使用的是 JSX,它只是被转换为 React.createElement 调用。
猜你喜欢
  • 2016-02-04
  • 2018-03-24
  • 2018-10-26
  • 2023-01-05
  • 2018-04-27
  • 2019-07-30
  • 2021-11-04
  • 2020-12-01
  • 1970-01-01
相关资源
最近更新 更多