通过 npm 使用 React前提是支持 Node.js 及 NPM
使用淘宝定制的 cnpm (gzip 压缩支持) 命令行工具代替默认的 npm:
$ npm install -g cnpm --registry=https://registry.npmmirror.com
$ npm config set registry https://registry.npmmirror.com
可以使用 cnpm 命令来安装:
$ cnpm install [name]
使用 create-react-app 快速构建 React 开发环境,执行以下命令创建项目:
$ cnpm install -g create-react-app
$ create-react-app my-app
$ cd my-app/
$ npm start
在浏览器中打开 http://localhost:3000/ ,结果如下图所示:
项目目录结构:
开始页面 index.html,这个是代码的源头。
修改 src/App.js 文件代码:
src/App.js
import logo from './logo.svg';
import './App.css';
import React, {Component} from "react";
class App extends Component{
render() {
return(
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<h2>Hello world!</h2>
</div>
<p className="App-intro">
你可以在<code>src/App.js</code>文件中修改。
</p>
</div>
);
}
}
// 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"
// target="_blank"
// rel="noopener noreferrer"
// >
// Learn React
// </a>
// </header>
// </div>
// );
// }
export default App;
修改后打开 http://localhost:3000/
,输出结果如下:
src/index.js 是一个入口文件,
实例
import React from 'react';
// import ReactDOM from 'react-dom/client';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(
// <React.StrictMode>
// <App />
// </React.StrictMode>
// );
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
// reportWebVitals();
function Hello(props){
return <h1>Hello wwwwwwworld!</h1>;
}
ReactDOM.render(<Hello />,document.getElementById('root'));
这时候浏览器打开 http://localhost:3000/
: