ReactJS 的 Hello world 示例程序
本文是一個篇ReactJS 的 Hello world 示例程序,是一個reactjs的入門教程,感興趣的同學參考下.
React.js 是 非死book 推出的一個用來構建用戶界面的 JavaScript 庫。
這篇文章提供了代碼實例和在React.js(一個非死book工程師開發的被用于構建用戶界面的Javascript庫)中高水平的概念.這些概念會被詳細的發表在下面的文章里.在此,我必須提示 如果你是一名ReactJS專家并且感覺這些代碼需要改善,請您把建議寫信給我,我會及時適當的更新這篇文章/代碼.
在我繼續發表一些代碼實例之前,我必須特別的提出:初學ReactJS會有一點困難,因為最近我一直在AngularJS上寫代碼.到現在為止,我需要承認他們之間在幫助我們做UI工作時有很大的不同.我將發表另一篇博文對比他們之間的主要差異.
然而,在較高的水平上,下面是一些原因關于我為何在學習 ReactJS 時使用了略有些“陡峭”的學習路線:
-
面向組件的:ReactJS是面向組件的,也就意味著,需要你將UI元素看作是組件。有趣的是,組件是可組合的。這意味著一個組件可以具有一個或多個內部組件。下面的代碼演示了這一點
-
JSX Syntax:它使用了一個有趣的JSX(XML式的)語法來編寫代碼。JSX轉換器(一個預編譯器)用來將這種語法結構轉換為明顯的JavaScript
-
事件代理模型:它遵循了事件委托模型,用以捕獲事件
下面是一些顯示在代碼中的關鍵概念:
-
組件
-
事件代理
-
JSX 語法
以下是組件已實現內容的簡要描述
- 輸入框元素,用戶可輸入其用戶名。在下面的文章中會提到,這個輸入框實際是“UserName”組件
- div層元素,用于展示“Hello, userName”。在下面的文章中會提到,這個div層實際是“HelloText”組件
以下是其如何設計的。此外,請找到能代表下面概念的代碼。
SayHello: 可組合的元件
SayHello是一個父組件,包含兩個組件。這個父組件是由兩個內部組件構成。其中一個組件是UserName,用來為用戶提供輸入姓名的功能,另一個組件是HelloText,用于展示文本,比如Hello,world。這個父組件定義了下列三個不同的API:
-
getInitialState
-
handleNameSubmit
-
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 appropriatelyhandleNameSubmit: 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組件有下列兩個方法:
-
handleChange:用來捕獲onChange事件
-
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:包含了展示HelloText組件內容的代碼
var HelloText = React.createClass({render: function() {return (<div><h3>Hello, {this.props.data}</h3></div>);}});
如果你希望得到全部的代碼,我已經將代碼掛在 github hello-reactjs page。請各位自由評論或給出建議。