JSX in Depth
JSX only supports syntactic sugar:
React.createElement(component, props, ...children)函数,
JSX code:
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
Compile compiles into:
React.createElement(
You can also use self_closing form of the tag if there are no children. So:
<div className="sidebar" />
compiles into:
In functional form:
function hello() {
return <div>Hello world!</div>;
}
translates to:
Regarding the format of React elements:
React must be in scope.
Using .Dot Notaiton , you can use dot notation in JSX. This is handy if a module is going to call out some React components. example:
A custom component must be capitalized (unless it is assigned a capitalized variable). function Hello (props){...}
Choosing the type at runtime
Expressions cannot be used as React element types. But it is possible to assign it to a variable with uppercase letters, and then you can use the JSX format indirectly
Props in JSX
With {}, any JS expression can be used as props. For example <MyComponent foo={1 + 2 + 3 + 4} />
if statements and for loops are not JS expressions and cannot be used directly in JSX. But {} will work
Conditional judgment Inline is written:
{true && expression} // If true, execute the expression.
{condition ? true : false }
Prevent the component from being rendered:
return null; ⚠️, the lifecycle method hook method of the component, still takes effect componentWillUpdate and componentDidUpdate.
Children in JSX
string Literals
<div>This is valid HTML & JSX at the same time.</div>
& is &
Compile:
JSX remove whitespace at the beginning and end of a line
JSX Children
Supports inline JSX elements as children. Useful in nested components.
React components also return array elements. return [, ,];
JS expressions can also be children.
//This is the function as props.children.
Function as Children
See the code marked in yellow. React.createElement(component, props,...child)
Booleans, Null, and Undefined are Ignored.
false , null, undefined, true are all children of validation, but they don't render.
So it can be used as a conditional judgment condition && expression.
Render <Header /> if showHeader is true
⚠️ 0 will be rendered
If you want to make true render use type conversion, String().
let description;if (props.number % 2 == 0) {description = <strong>even</strong>;} else {description = <i>odd</i>}return <div>{props.number} is an {description} number</div>;}with