简体   繁体   中英

Include React to existing web page - multiple react components

I am trying to include React to an web page. i would like to break up the components into it's own .js files. i am not having any luck.

My index.html file looks like this.

<html>  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <title>Hello React!</title>
    <script src = "https://unpkg.com/react@16/umd/react.development.js ">/script>
    <script src = "https://unpkg.com/react-dom@16/umd/react-dom.development.js "></script>
    <script src = "https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>   
  </head>
  <body>
    <div id="root"> 
    </div>
    <script src="app.js" type="text/babel"> </script>
    <script src="greetings.js" type="text/babel"> </script> 
  </body>

My app.js file looks like this.

class App extends React.Component {
        render() {
          return (
           <div>
             <Greetings />
             <h1>Hello World!</h1>
           </div>
             )
          }
      }

ReactDOM.render(<App />, document.getElementById('root'))

My greetings.js file looks like this

class Greetings extends React.Component {
        render() {
          return <h1>Hi</h1>
 }
}

So i was expecting "Hi" followed by "Hello world!" but i am getting "Greetings is not defined".

Can you help me?

I am answering my own question. The order which loads the .js files was the problem. it has to be

<script src="greetings.js" type="text/babel"> </script> 
<script src="app.js" type="text/babel"> </script>

Then it displayed the web page correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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