反应不渲染道具?

时间:2016-08-04 22:31:16

标签: javascript reactjs properties react-dom

因此,出于某种原因,反应不会在我的简单应用中呈现我的txt属性。 这是我在App.js文件中的代码:

import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
  render() {
    return <h1> {this.props.txt}</h1>

  }
}
ReactDOM.render(<App txt="Hello world"/>, document.getElementById('app'))

这是我在chrome developer tools console中遇到的错误:

index.js:9576 Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).warning @ index.js:9576createElement @ index.js:26847(anonymous function) @ index.js:7558__webpack_require__ @ index.js:20(anonymous function) @ index.js:48__webpack_require__ @ index.js:20(anonymous function) @ index.js:40(anonymous function) @ index.js:43
index.js:8492 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

2 个答案:

答案 0 :(得分:0)

代码很好..必须是其他东西的问题(也许是webpack或babel设置?)

See example below

https://jsfiddle.net/9dnu3pt8/

答案 1 :(得分:0)

您的代码很好并且应该可以使用,您的环境有什么用,您使用的是webpack吗?如果是这样,您需要添加一些预设才能与ecma 2015一起使用。

跟随package.json文件

的示例
{
  "name": "project",
  "version": "0.0.0",
  "description": "",
  "author": "",
  "license": "BSD-2-Clause",
  "dependencies": {
    "react-dom": "~15.3.0",
    "react": "~15.3.0"
  },
  "devDependencies": {
    "webpack": "~1.13.1",
    "babel-loader": "~6.2.4",
    "babel-preset-react": "~6.11.1",
    "babel-core": "~6.11.4",
    "babel-preset-es2015": "~6.9.0"
  }
}

webpack.config.js文件

module.exports = {
    entry: "./app/App.js",
    output: {
        filename: "public/bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    presets: ['react', 'es2015']
                }
            }
        ]
    }
}