D2.Reactjs 操作事件、狀態改變、路由

來源:互聯網
上載者:User

標籤:tor   app   改變   als   super   hand   install   ons   local   

下面內容代碼使用ES6文法

一、組件的操作事件:

1、先要在組件類定義內定義操作事件的方法,如同event handler。若我需要監聽在組件內的Button的點擊事件onClick,首先定義監聽方法,代碼如下:

 handleClick() {//TODO}

 

2、在contructor 函數,bind(this)。

 constructor(props) {        super(props);        this.handleClick = this.handleClick.bind(this);    }

 

3、在render方法內,顯式綁定事件

 render() {        return <div>            <button onClick={this.handleClick}>click</button>        </div>;    }

經過以上操作即會觸發監聽事件方法

 

二、組件狀態state

  組件,我理解其實就是wpf的控制項,那麼state就是wpf中的相依性屬性了,其功能如相依性屬性其中的功能很類似,state的改變會改變組件的UI變化或者進行一些邏輯操作。

1、設定初始狀態,即在contructor函數上設定組件初始state,

 constructor(props) {        super(props);        this.state = {            liked: false,            opacity: 1        };    }

2、在事件中可以利用setState()設定新的狀態,如在handleclick事件改變state,如下:

handleClick() {        this.setState({ liked: !this.state.liked });    }

state改變後促使組件重新執行render(),進而改變了UI。

 

三、路由

  reactjs可以使用單頁面搭建整個網站或者APP,那麼路由機制就十分需要,方便我們來實際一個頁面來構建多個頁面和頁面的架構。React-Router是一個十分實用的官方外掛程式,提供進行導航等操作。

1、安裝外掛程式

npm install -S react-router

2、使用

使用react-router 就像使用一般的外掛程式,如下:

import React from ‘react‘;import { render } from ‘react-dom‘;import { Router, Route,IndexRoute, Link, browserHistory, hashHistory } from ‘react-router‘;import App from ‘./compoments/App‘;import ABout from ‘./compoments/ABout‘;import Home from ‘./compoments/Home‘;render((<Router history={browserHistory}>    <Route path="/" component={App} >     <IndexRoute component={Home}/>        <Route path="/home" component={Home} />        <Route path="/about" component={ABout} />    </Route></Router>), document.getElementById("container"));

其中App,Home,About 都是其他檔案定義的組件。

  Router的history屬性設定是設定Router將使用哪種URL,例如使用hashHistory,路由的切換由URL的hash變化決定,即URL的#部分發生變化,即上面訪問about頁面,URL路徑將是localhost:8080/#/about;例如使用browserHistory,將會呼叫瀏覽器的URL,即訪問about頁面,URL路徑將是localhost:8080/about。

  更多Router參數設定可以去官網查看。

D2.Reactjs 操作事件、狀態改變、路由

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.