使用 React.js 顯示 hello world


create-react-app 是一個用於建立具有預設配置的 React.js 專案的命令。Create-react-app 將幫助執行 React 應用程式。命令將在 npm 或 yarn 上執行。

如果計算機上安裝了 npm 和 node.js,請使用以下命令全域性安裝 create-react-app:

npm install –g create-react-app

專案建立 - 要在執行上述命令後建立專案,請執行以下命令:

npx create-react-app hello-world-example

npx 自 npm 5.2+ 版本起提供,可以使用 npm –version 在終端中檢查 npm 版本。

如果 npm 版本為 5.2+,則可以使用以下命令直接建立 React.js 專案:

npx create-react-app hello-world-example

如果 npm 版本為 6+,npm init react-app hello-world 也是建立 React.js 專案的一個選項。

使用 yarn,我們有以下命令:yarn create react-app hello-world-example

完成上述命令後,更改目錄到 hello-world-example

使用 create-react-app,預先配置了使用高階 JavaScript 功能所需的 webpack 或 babel,我們只需專注於編寫程式碼即可。

cd hello-world-example

要執行應用程式,請在終端上執行以下命令:

npm start

npm start 執行一個即時開發伺服器,程式碼更改將自動重新整理瀏覽器並反映更改。

將開啟一個瀏覽器視窗,如果未自動開啟,請手動開啟瀏覽器並在位址列中輸入 url:localhost:30003000 是 React 應用程式中使用的預設埠。如果埠號有任何問題,可以更改埠號。

應用程式執行時的預設文字如下所示:

顯示

要更新,請使用任何程式碼編輯器工具(例如 Visual Studio Code)開啟專案。

開啟檔案 App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
   return (
      <div className="App">
         <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>Edit <code>src/App.js</code> and save to reload.</p>
            <a
               className="App-link"
               href="https://reactjs.org.tw"
               target="_blank"
               rel="noopener noreferrer">
               Learn React
            </a>
         </header>
      </div>
   );
}
export default App;

將 return 語句的內容更改為僅 hello World 文字:

import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
   return (
      <div className="App">
         Hello World !
      </div>
   );
}
export default App;

瀏覽器上的文字將立即更改。

更新於: 2019年8月28日

11K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告