给定以下HTML文件:
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react.js"></script> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.js"></script> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script> </head> <body> <div id="content"></div> <script type="text/babel" xx_src="scripts/example.js"></script> </body> </html>
您可以在单独的文件中使用以下代码创建基本组件:
脚本/example.js
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class FirstComponent extends Component { render() { return ( <div className="firstComponent"> Hello, world! I am a FirstComponent. </div> ); } } ReactDOM.render( <FirstComponent />, // 请注意,这与您上面存储的变量相同 document.getElementById('content') );
您将得到以下结果(请注意里面的内容div#content):
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react.js"></script> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.js"></script> <script xx_src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script> </head> <body> <div id="content"> <div className="firstComponent"> Hello, world! I am a FirstComponent. </div> </div> <script type="text/babel" xx_src="scripts/example.js"></script> </body> </html>