简体   繁体   English

我的“ Hello World”示例出了什么问题?

[英]What is wrong in my “Hello World” example?

I learn ReactJS and try to use it through the "clear ReactJS". 我学习了ReactJS,并尝试通过“清除ReactJS”来使用它。

This is my simple code: 这是我的简单代码:

 class MyList extends React.Component{ constructor(data){ super(data) this.text = data.text } render(){ return React.createElement("h1", null, this.props.text) } } const root = document.getElementById("root") const component = new MyList({text:"abcdefgh"}) ReactDOM.render(component,root) 
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

But it doesn't work. 但这是行不通的。 Why it doesn't work? 为什么不起作用?

Thank you. 谢谢。

The error is in your const component line. 错误在您的const组件行中。 The first argument of your ReactDOM.render function should be an actual component. ReactDOM.render函数的第一个参数应该是实际的组件。 Components are generated by using React.createElement (just like you did in your render() function for your MyList component. Here is a working example: https://jsbin.com/lejuwet/1/edit?html,js,output 组件是通过使用React.createElement生成的(就像您在MyList组件的render()函数中所做的那样。这是一个有效的示例: https ://jsbin.com/lejuwet/1/edit?html,js,output

class MyList extends React.Component{

        constructor(data){
            super(data)
            this.text = data.text
        }

        render(){
          console.log("render");
            return React.createElement("h1", null,
            this.props.text)
        }
    }

const root = document.getElementById("root")
const component = new React.createElement(MyList, {text: "123"});
ReactDOM.render(component, root)

You are using older version of ReactJS. 您正在使用旧版本的ReactJS。 This is how it looks with React v16. 这就是React v16的外观。

import React,{ Component } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends Component {

  constructor(props) {
    super(props)
  }

  render() {
    return(
      <h1>Hello World</h1>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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