react入坑指南

本篇为萌新篇.

  • 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.注意跨域问题;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 现在最热门的前端框架,毫无疑问是 React 。上周,基于 React 的 React Native 发布,结果一...
    sakura_L阅读 3,196评论 0 0
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,503评论 0 23
  • 对抗岁月的侵袭, 除了容颜的加持, 更需要内在力量的修养... 《楚辞·九歌》 ...
    墨影teresa阅读 6,187评论 22 52
  • 阅读书目:颠覆平庸Part1-5 阅读时间:45分钟(番茄钟) 阅读困难:时间预测不是很准确,计划一个番茄钟,实际...
    滨鸿阅读 1,612评论 0 0

友情链接更多精彩内容