JSX
JSX is a react syntax that combines common high-level programming language syntax with html syntax: const element = <h1>Hello, world!</h1>
, and it can also be treated as a expression to be returned.
Compile principle
JSX forms:
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);```
Babel compiles JSX to `React.createElement()` and it creates an object like this:
const element = {
type: 'hi',
props: {
className: 'greeting',
children: 'Hello, world'
}
};```
Elements & Rendering
- Elements are what components are "made of".
- To reander a React element into a root DOM node, pass both to
ReactDOM.render()
:
ReactDOM.render(
element,
document.getElementById('root')
);
- Elements are immutable.
- React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
Components and Props
- Method one(JavaScript function):
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
- Method two(ES6 class):
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
- Elements can also represent user-defined components ( call the function, followed by the parameters):
const element = <Welcome name="Sara" />
. If the component takes no parameters, than we can directly call the component inside the React render. - Components must return a single root element.
- All React conponents must act like pure function s with respect to their props.
网友评论