ReactJs入門指南
React是什么?
React.js 是 非死book 推出的一個用來構建用戶界面的 JavaScript 庫。
React中,把一切東西都看成組件,而且所有組件有其狀態。
什么是狀態?簡單來說,一個組件有多種有限的狀態,但同時只能是一種狀態,不過條件處罰就會變成另一種狀態。學術上叫有限狀態機。
從評論這個組件說起,評論組件整體叫做CommentBox,這個父組件有兩個子組件:CommentList和CommentForm,CommentList中又包含Comment這個小組件。
從CommentBox開始
先來看看最大的CommentBox,創建一個叫CommentBox組件,然后可以用這個名字作為標簽名實例化。里面包含兩個子組件。數據我們可以從屬性上傳進去。
var data = [
{author: "Pete Hunt", text: "This is one comment"},
{author: "Jordan Walke", text: "This is *another* comment"}
];
var CommentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="commentBox">
<CommentList data={this.state.data} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function (comment) {
return (
<Comment author={comment.author}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
React.render(
<CommentBox url="comments.json" pollInterval={2000}/>,
document.getElementById('content')
);在React中,最重要的兩個點之一就是這個props,可以通過組件的屬性來傳遞數據。上面的代碼就可以展現出評論的列表。
獲取服務器的數據
那么如何獲取服務器數據?這個時候就需要引入一開始說的狀態state。
var CommentForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var author = this.refs.author.getDOMNode().value.trim();
var text = this.refs.text.getDOMNode().value.trim();
if (!text || !author) {
return;
}
this.refs.author.getDOMNode().value = '';
this.refs.text.getDOMNode().value = '';
this.props.onCommentSubmit({author: author, text: text});
return;
},
render: function() {
return (
<form className="commentForm">
<input type="text" placeholder="Your name" />
<input type="text" placeholder="Say something..." />
<input type="submit" value="Post" />
</form>
);
}
});
var CommentBox = React.createClass({
handleCommentSubmit: function(comment) {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!