在使用React腳手架之前需要通過 create-react-app 快速構建 React 開發環境 ,
注意 : create-react-app 自動創建的項目是基於 Webpack + ES6 。
執行以下命令創建項目:
$ npm install -g create-react-app
$ create-react-app myapps
$ cd myapps/
$ npm start
在安裝成功后開始使用腳手架
圖為安裝成功后的目錄
在使用React之前需要注意以下三點:
一 . 關於 class 的問題
在 React 中元素的 class 需要換成 className
二 . 圖片路徑的問題
1 . 如果要使用相對路徑引入圖片有兩種方法:( 相對路徑用於請求 src 下面的圖片)
每個組件類中引入圖片當使用相對路徑的時候,這個圖片必須放在src中。
a . 直接在組件類的模板中通過 require("文件的相對路徑") 引入
<img src={require("../images/01.jpg")} alt="圖片"/>
b . 通過定義圖片,在模板中調用
// 引入並定義圖片 import pic from './images/01.jpg'; // 在模板中使用 <div className="App"> <img src={pic} alt="圖片"/> </div>
2 . 如果在 public 中放了一張圖片,我們會發現在地址欄上輸 http://localhost:3000/01.jpg 能找到圖片,說明 React 把 public 當做該項目的 web 容器。 所以,以后做項目時靜態資源放在 public 中。
因此,我們的 ajax 請求和 鈎子函數 的路徑就相對於 index.html , 下面是 ajax請求本地文件 aa.txt 實例
import React, { Component } from 'react'; // npm install axios 下載並引入 axios import axios from "axios"; // 創建類組件 組件類的創建方法
// 第一 React.createClass() 最開始的
// 第二 class Heads extend Component{}
// 第三 構造函數
class Slide extends Component { constructor(props){ // 在該組件類的標簽中設置 props 值,這里設置的是 title super(props); this.state={ // 設置state url:"http://localhost:3000/images/01.jpg" } } render() { return ( <div className="slide"> <div> <img src={this.state.url} alt="圖片"/> </div> </div> ); } componentDidMount(){ axios.get(this.props.title) .then(function (res) { console.log(res.data); this.setState({ "url":res.data }) }.bind(this)) .catch(function (err) { console.log(err); }) } } export default Slide;
上面組件中設置 props 值
// title 與上面組件中的值對應 <Slide title="http://localhost:3000/txt/aa.txt"/>
三 . 事件
事件通常和 this 有關,下面是關於事件的例子
import React, { Component } from 'react'; class Heads extends Component { //創建組建類 constructor(){ super() this.state={ title:"welcom to China" } this.fn=this.fn.bind(this) } fn(){ // 事件往往和this有關 this.setState({ title:"Hello world!" }) } render() { return ( <div className="Heads"> <h3 onClick={this.fn}> {this.state.title} </h3> </div> ); } } export default Heads;
在學習 React 時,一定要注意:
ajax請求和鈎子函數 路徑就要相對index.html,所以資源需要放在public下,因為public是靜態資源。