這篇文章提供了代碼實例和在React.js(一個Facebook工程師開發的被用於構建用戶界面的Javascript庫)中高水平的概念.這些概念會被詳細的發表在下面的文章裡.在此,我必須提示如果你是一名ReactJS專家並且感覺這些代碼需要改善,請您把建議寫信給我,我會及時適當的更新這篇文章/代碼.
在我繼續發表一些代碼實例之前,我必須特別的提出:初學ReactJS會有一點困難,因為最近我一直在AngularJS上寫代碼.到現在為止,我需要承認他們之間在幫助我們做UI工作時有很大的不同.我將發表另一篇博文對比他們之間的主要差異.
然而,在較高的水平上,下面是一些原因關於我為何在學習 ReactJS 時使用了略有些“陡峭”的學習路線:
事件代理模型:它遵循了事件委托模型,用以捕獲事件
下面是一些顯示在代碼中的關鍵概念:
以下是組件已實現內容的簡要描述
- 輸入框元素,用戶可輸入其用戶名。在下面的文章中會提到,這個輸入框實際是“UserName”組件
- div層元素,用於展示“Hello, userName”。在下面的文章中會提到,這個div層實際是“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:包含了展示HelloText組件內容的代碼
var HelloText = React.createClass({
render: function() {
return (
<div>
<h3>Hello, {this.props.data}</h3>
</div>
);
}
});
如果你希望得到全部的代碼,我已經將代碼掛在 github hello-reactjs page。請各位自由評論或給出建議。