React 腳手架應用以及注意事項

  在使用React腳手架以前須要經過  create-react-app 快速構建 React 開發環境 ,html

    注意 : create-react-app 自動建立的項目是基於 Webpack + ES6 react

  執行如下命令建立項目:ios

   $ npm install -g create-react-appweb

   $ create-react-app myappsajax

   $ cd myapps/npm

   $ npm startaxios

  在安裝成功後開始使用腳手架app

      圖爲安裝成功後的目錄ide

  在使用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是靜態資源。

相關文章
相關標籤/搜索