React教程系列之原理篇

前端之家收集整理的这篇文章主要介绍了React教程系列之原理篇前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

React里面有一个规范:

Note:

The comment parser is very strict right now; in order for it to pick up the@jsxmodifier,two conditions are required.

The@jsxcomment block must be the first comment on the file.

The comment must start with/**(/*and//will not work).

If the parser can't find the@jsxcomment,it will output the file without transforming it.

实例:

/** @jsx React.DOM */
React.renderComponent(
  React.DOM.h1(null,'Hello,world!'),document.getElementById('example')
);

出于好奇,看了一下实现,还真是有点收获:

facebook有一个JSXTransformer.js的工具,做一些js的parse工作

var docblock = require('jstransform/src/docblock');

这个jstransform哪里有呢?

这个东西可以做很多事情,看了一下源码

var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/;
var ltrimRe = /^\s*/;
/**
 * @param {String} contents
 * @return {String}
 */
function extract(contents) {
  var match = contents.match(docblockRe);
  //match == > ["/** @jsx React.DOM */","/** @jsx React.DOM */"," "]
  if (match) {
    //这部分是去掉开始的空格
   //比如    /** @jsx React.DOM */这种会过滤前面的空格
    return match[0].replace(ltrimRe,'') || '';
  }
  return '';
}

function parseAsObject(docblock) {
  var pairs = parse(docblock);
  //pairs ==> [["jsx","React.DOM"]]
  var result = {};
  for (var i = 0; i < pairs.length; i++) {
    result[pairs[i][0]] = pairs[i][1];
  }
  return result;
}

猜你在找的React相关文章