本篇为萌新篇.
- 1.定义的类名必须以大写字母开头,如:
var DemoFunction = React.createClass({ });
就不能写成
var demoFunction = React.createClass({ });
- 2.组件类中只能包含一个顶层标签,如:
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.接上条,其实可以调用
dangerouslySetInnerHtml()
方法输出HTML的原本内容,这样可以避免react对标签等的限制,如下例(根据官方文档的编码习惯修改,可能这就是所谓的模块化和组件化思想?):
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.根据官方文档的说明,使用这个方法时必须注意来自外部的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);
});
关于fetch
需要注意的是:
1.根据MDN的Browser compatibility,fetch
的浏览器支持情况需要被慎重考虑,引用es6-promise.js
可以解决部分老旧浏览器的兼容性问题;
2.fetch与react本身无关,是基于es6实现,返回的是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.每次进行fetch
会话的时候默认会创建新的session key, 在服务端同步数据的时候需要注意;
4.注意跨域问题;