Guest User

Untitled

a guest
Mar 17th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. # JSX 简介
  2.  
  3. [TOC]
  4.  
  5. JSX 是 JavaScript 一种语法扩展,可以很方便的描述某一块 UI 应该长什么样子。
  6.  
  7. 所有的 JSX 最终会转译成 `React.createElement`,因此最终输出的是一个 Element 元素(ReactElement 或者 CustomElement 等)。
  8.  
  9. ## 使用 `{}` 表达式
  10.  
  11. 在 JSX 可以使用任意 JavaScript 表达式,用大括号 `{}` 括起来。
  12.  
  13. ```js
  14. const element = (
  15. <h1 className={ this.props.className }>
  16. Hello, { formatName(user) }!
  17. </h1>
  18. );
  19. ```
  20.  
  21. 另外,对于多行 JSX 语句,为了避免 _自动分号插入_,需要用圆括号 `()` 将整个 JSX 括起来。
  22.  
  23. ## JSX 自身也是一个表达式
  24.  
  25. JSX 最终会返回 Element 元素,也是一个表达式。
  26.  
  27. ```js
  28. function getGreeting(user) {
  29. if (user) {
  30. // return React.createElement('h1', ...)
  31. return <h1>Hello, {formatName(user)}!</h1>;
  32. }
  33. // return React.createElement('h1', ...)
  34. return <h1>Hello, Stranger.</h1>;
  35. }
  36. ```
  37.  
  38. ## 在 JSX 中指定属性
  39.  
  40. 对于字符串常量,直接使用引号即可。
  41.  
  42. ```js
  43. const element = <div tabIndex="0"></div>;
  44. ```
  45.  
  46. 对于其他的属性值,使用 `{}` 表达式进行计算即可。
  47.  
  48. ```js
  49. const element = <img src={user.avatarUrl}></img>;
  50. ```
  51.  
  52. ## JSX 部分属性名变驼峰风格
  53.  
  54. 由于 JSX 更加偏向于 JavaScript,React DOM 使用了属性的驼峰风格,例如 `class` 需要写成 `className`,`tabindex` 需要写成 `tabIndex`。
  55.  
  56. ## JSX 中指定子节点
  57.  
  58. 如果元素没有子节点,类似 HTML 中的 `img` 元素,直接关闭即可。
  59.  
  60. ```js
  61. const element = <img src={user.avatarUrl} />;
  62. ```
  63.  
  64. 如果元素包含子节点,使用圆括号括起来。
  65.  
  66. ```js
  67. const element = (
  68. <div>
  69. <h1>Hello!</h1>
  70. <h2>Good to see you here.</h2>
  71. </div>
  72. );
  73. ```
  74.  
  75. ## JSX 会自动防 XSS 注入
  76.  
  77. JSX 的 `{}` 表达式会自动对一些危险字符进行转义(例如 &、<、>、"、'),因此可以避免 XSS 攻击。
  78.  
  79. ```js
  80. const title = response.potentiallyMaliciousInput;
  81. // This is safe:
  82. const element = <h1>{title}</h1>;
  83. ```
  84.  
  85. ## JSX 的本质
  86.  
  87. Babel 会将 JSX 转译成 `React.createElement()` 调用。
  88.  
  89. 下边两个语法返回结果是一样的,因此可以看到 JSX 不是必要的,但是使用 JSX 更加简洁。
  90.  
  91. ```js
  92. const element = (
  93. <h1 className="greeting">
  94. Hello, world!
  95. </h1>
  96. );
  97. ```
  98.  
  99. ```js
  100. const element = React.createElement(
  101. 'h1',
  102. {className: 'greeting'},
  103. 'Hello, world!'
  104. );
  105. ```
  106.  
  107. 它们最终会创建一个类似如下的一个对象:
  108.  
  109. ```js
  110. const element = {
  111. type: 'h1',
  112. props: {
  113. className: 'greeting',
  114. children: 'Hello, world'
  115. }
  116. };
  117. ```
  118.  
  119. 这些对象被称作 "React elements",之后 React 读取这些对象取创建和更新 DOM。
Add Comment
Please, Sign In to add comment