JSX In Depth
JSX将通过Babel进行编译.
标准首位标签格式
1 | <MyButton color="blue" shadowSize={2}> |
compiles into:
1 | React.createElement( |
自闭合标签格式
You can also use the self-closing form of the tag if there are no children. So:
1 | <div className="sidebar" /> |
compiles into:
1 | React.createElement( |
Specifying The React Element Type
一般Component使用大写字母开头, 如果在当前JSX里面使用 <XXX/>
那么XXX这个Component就必须出现在Scope之内.
另外可以使用
import
语句将Component引用到Scope内
Using Dot Notation for JSX Type
1 | import React from 'react'; |
User-Defined Components Must Be Capitalized
自定义Component(比如 <MyComponent/>
)应该大写字母开头
系统自带的Component(比如 <div/>
)应该小写字母开头
否则系统会抛出警告
Choosing the Type at Runtime
注意JSX Obj的tags必须是完整的单词, 如果想要动态生成tag名称可以用赋值的办法
错误的例子:
1 | function Story(props) { |
正确的做法:
1 | function Story(props) { |
Prop in JSX
JavaScript Expressions as Props
关于使用JS表达式作为prop:
1 | <MyComponent foo={1 + 2 + 3 + 4} /> |
If condition within JSX
不能够直接使用, 但是可以用这个替代方法:
1 | function NumberDescriber(props) { |
另外一个很实用的条件判断的snippet
This can be useful to conditionally render React elements. This JSX only renders a <Header />
if showHeader
is true
:
1 | <div> |
String Literals
When you pass a string literal, its value is HTML-unescaped. So these two JSX expressions are equivalent:
1 | <MyComponent message="<3" /> |
Props Default to “True”
If you pass no value for a prop, it defaults to true. These two JSX expressions are equivalent:
1 | <MyTextBox autocomplete /> |
Spread Attributes
If you already have props
as an object, and you want to pass it in JSX, you can use ...
as a “spread” operator to pass the whole props object. These two components are equivalent:
提供Props时, 若有一个Obj并且这个Obj里面所有Attr和需要的Prop相匹配, 那么可以使用
spread
operator 进行赋值
1 | function App1() { |
另外对于 spread
operator也可以给部分值赋值:
1 | const Button = props => { |
关于解构运算符
MDN参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
这玩意是ES6新引进的运算符, 通过三个点进行引用 ...
1 | function sum(x,y,z){ |
在老版本ES6中, 对Obj进行解构赋值会报错, 但是JSX中允许这样的使用.
Children in JSX
子元素全部会通过 props.children
进行引用.
另外如果没有子tag而只是放置了一段文本, 那么props.children
就会是tag之间的一段字符串
Hint: HTML is unescaped!
1 | <MyComponent>Hello world!</MyComponent> |
tags之间的空格和空行都会被忽略.
1 | <div> |
另外也可以将JS表达式用于child elem. 比如一个很典型的使用数组循环生成列表的例子:
1 | return ( |
Functions as Children
反正只要最后返回的是一个完整的JSX Obj即可
1 |
|
Booleans, Null, and Undefined Are Ignored
false
, null
, undefined
, and true
are valid children. They simply don’t render. These JSX expressions will all render to the same thing:
1 | <div /> |