本篇為萌新篇.
- 1.定義的類名必須以大寫字母開頭,如:
var DemoFunction = React.createClass({ });
就不能寫成
var demoFunction = React.createClass({ });
- 2.組件類中只能包含一個頂層標(biāo)簽,如:
var DemoFunction = React.createClass({
render: function() {
return (
<div class="topdiv">
<span>Hello React!</span>
<span>Hello React Again!</span>
</div>
);
}
});
不能寫成
var DemoFunction = React.createClass({
render: function() {
return (
<div class="topdiv">
<span>Hello React!</span>
<span>Hello React Again!</span>
</div>
<div class="topdiv2">
<span>Hello React!</span>
<span>Hello React Again!</span>
</div>
);
}
});
- 3.接上條,其實可以調(diào)用
dangerouslySetInnerHtml()方法輸出HTML的原本內(nèi)容,這樣可以避免react對標(biāo)簽等的限制,如下例(根據(jù)官方文檔的編碼習(xí)慣修改,可能這就是所謂的模塊化和組件化思想?):
var DemoFunction = React.createClass({
htmlContent: function() {
var html = "<div class='topdiv'><span>Hello React!</span><span>Hello React Again!</span></div><div class='topdiv2'><span>Hello React!</span><span>Hello React Again!</span></div>";
return {__html: html};
},
render: function() {
return (
<div dangerouslySetInnerHTML={this.htmlContent()}></div>
);
}
});
這里需要注意的是:
1.聲明的HTML字符串不能有換行等,否則將不能被解析;
2.根據(jù)官方文檔的說明,使用這個方法時必須注意來自外部的XSS攻擊:
dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.
另外,個人建議把return方法用小括號( )包起來;
- 4.react不提供形如
$.ajax()之類的方法,而引入JQuery將不可避免的使得頁面變得臃腫,因而我們可以嘗試使用fetch來解決該問題:
fetch("https://api.xxxx.xxx/xxx").then(function(response){
console.log(response);
});
關(guān)于fetch
需要注意的是:
1.根據(jù)MDN的Browser compatibility,fetch的瀏覽器支持情況需要被慎重考慮,引用es6-promise.js可以解決部分老舊瀏覽器的兼容性問題;
2.fetch與react本身無關(guān),是基于es6實現(xiàn),返回的是promise對象;
The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a promise that resolves to the Response
to that request, whether it is successful or not. You can also optionally pass in an init options object as the second argument (see Request
).
3.每次進(jìn)行fetch會話的時候默認(rèn)會創(chuàng)建新的session key, 在服務(wù)端同步數(shù)據(jù)的時候需要注意;
4.注意跨域問題;