DIV CSS 佈局教程網

從 ReactJS 的 Hello World 說起
編輯:關於JavaScript     

本文通過代碼實例,介紹 React.js(一個由 Facebook 工程師開發、用於構建用戶界面的 JavaScript 庫)中的一些高水平概念,這些概念會在後文中逐一展開。如果你是 ReactJS 專家,並覺得這些代碼還有改進空間,歡迎寫信給我,我會及時、恰當地更新本文。

在繼續之前,我要特別說明:由於我最近一直在寫 AngularJS,初學 ReactJS 時難免會感到有些不適。到目前為止,我必須承認,二者在幫助我們完成 UI 工作上有很大不同,我會另寫一篇博文來對比它們的主要差異。

不過從較高的層面看,以下幾點說明了我在學習 ReactJS 時為何選擇了一條略顯「陡峭」的路線:

  • 面向組件:ReactJS 是面向組件的,這意味著你需要把 UI 元素都看作組件。有趣的是,組件是可組合的——一個組件內部可以包含一個或多個組件,下面的代碼便演示了這一點。
  • JSX 語法:它使用了一套頗具特色的 JSX(XML 式)語法來編寫代碼,並通過 JSX 轉換器(一個預編譯器)把這種語法結構轉換為常規的 JavaScript。
  • 事件代理模型:它遵循事件委托模型來捕獲事件。

下面是一些將在代碼中體現的關鍵概念:組件、事件代理、JSX 語法。

組件已實現的功能簡述

- 一個輸入框元素,供用戶輸入用戶名,它就是後文中的「UserName」組件;

- 一個 div 層元素,用於展示「Hello, userName」,它就是後文中的「HelloText」組件。

它們的設計思路如下,敬請參照後文對應概念的代碼。

SayHello:可組合的組件

SayHello 是一個父組件,由兩個內部組件構成:UserName 負責讓用戶輸入姓名,HelloText 負責展示「Hello, World」這樣的文本。這個父組件定義了三個不同的 API:

  1. getInitialState
  2. handleNameSubmit
  3. render(這是必需接口,組件需要定義 render 來告訴 React 如何渲染)
 // This is the parent component comprising of two inner components // One of the component is UserName which is used to allow user to enter their name // Other component is HelloText which displays the text such as Hello, World // var SayHello = React.createClass({ // This is used to set the state, "data" which is // accessed later in HelloText component to display the updated state // getInitialState: function() { return {data: 'World'} }, // It is recommended to capture events happening with any children // at the parent level and set the new state that updates the children appropriately handleNameSubmit: function(name) { this.setState({data: name}); }, // Render method which is comprised of two components such as UserName and HelloText // render: function() { return( <div> <UserName onNameSubmit={this.handleNameSubmit}/> <HelloText data={this.state.data}/> </div> ); } });

UserName 組件

UserName 組件有以下兩個方法:

  1. handleChange:用來捕獲 onChange 事件;
  2. render:用於渲染組件。
 var UserName = React.createClass({ handleChange: function() { var username = this.refs.username.getDOMNode().value.trim(); this.props.onNameSubmit({username: username }); this.refs.username.getDOMNode().value = ''; return false; }, render: function() { return( <form role="form" onChange={this.handleChange}> <div className="input-group input-group-lg"> <input type="text" className="form-control col-md-8" placeholder="Type Your Name" ref="username"/> </div> </form> ); } });

HelloText 組件

HelloText 組件只有一個用於渲染的方法 render,其中包含展示組件內容的代碼:

 var HelloText = React.createClass({ render: function() { return ( <div> <h3>Hello, {this.props.data}</h3> </div> ); } });

從這個小小的 Hello World 出發,我們不難體會 React 面向組件、可組合、基於 JSX 與事件代理的設計哲學。如果你希望獲取全部代碼,我已將其掛在 github 的 hello-reactjs 頁面,歡迎大家自由評論或提出建議。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved