Web前端之路WEB前端程序开发

react入坑指南

2017-06-05  本文已影响78人  Separes

本篇为萌新篇.

var DemoFunction = React.createClass({ });

就不能写成

var demoFunction = React.createClass({ });
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>
      );
  }
});
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方法用小括号( )包起来;

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

上一篇 下一篇

猜你喜欢

热点阅读