本文通過代碼實例,介紹 React.js(一個由 Facebook 工程師開發、用於構建用戶界面的 JavaScript 庫)中的一些高水平概念,這些概念會在後文中逐一展開。如果你是 ReactJS 專家,並覺得這些代碼還有改進空間,歡迎寫信給我,我會及時、恰當地更新本文。
在繼續之前,我要特別說明:由於我最近一直在寫 AngularJS,初學 ReactJS 時難免會感到有些不適。到目前為止,我必須承認,二者在幫助我們完成 UI 工作上有很大不同,我會另寫一篇博文來對比它們的主要差異。
不過從較高的層面看,以下幾點說明了我在學習 ReactJS 時為何選擇了一條略顯「陡峭」的路線:
下面是一些將在代碼中體現的關鍵概念:組件、事件代理、JSX 語法。
組件已實現的功能簡述
- 一個輸入框元素,供用戶輸入用戶名,它就是後文中的「UserName」組件;
- 一個 div 層元素,用於展示「Hello, userName」,它就是後文中的「HelloText」組件。
它們的設計思路如下,敬請參照後文對應概念的代碼。
SayHello:可組合的組件
SayHello 是一個父組件,由兩個內部組件構成:UserName 負責讓用戶輸入姓名,HelloText 負責展示「Hello, World」這樣的文本。這個父組件定義了三個不同的 API:
// 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 組件有以下兩個方法:
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 頁面,歡迎大家自由評論或提出建議。