react
使用JSX来编写的组件会被编译成调用React.createElement的形式
class App extends Component {
render() {
return (
<p src={logo} className="App-logo">Edit <code>src/App.js</code> and save to reload.</p>
)
}
}
经过Babel编译后:
React.createElement(
"p",
{ src: logo, className: "App-logo"},
"Edit ",
React.createElement(
"code",
null,
"src/App.js"
),
" and save to reload."
)
看createElement源码:
function createElement(type, config, children) {
...
// 返回出ReactElement
return ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
}
之后ReactElement
const ReactElement = function(type, key, ref, self, source, owner, props) {
const element = {
// Symbol类型的tag唯一标示这个对象是一个React Element类型
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE, // REACT_ELEMENT_TYPE:Symbol.for('react.element')
// Built-in properties that belong on the element
type: type, // 如果当前ReactElement是一个ReactComponent,那这里将是它对应的Constructor;而普通HTML标签,一般都是String
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner,
};
return element;
};
ReactElement主要分为DOM Elements和Component Elements两种,我们称这样的对象为ReactElement。
{
type: 'button',
props: {
className: 'button button-blue',
children: {
type: 'b',
props: {
children: 'OK!'
}
}
}
}
class Button extends React.Component {
render() {
const { children, color } = this.props;
return {
type: 'button',
props: {
className: 'button button-' + color,
children: {
type: 'b',
props: {
children: children
}
}
}
};
}
}
// Component Elements
{
type: Button,
props: {
color: 'blue',
children: 'OK!'
}
}