1、写类组件时,继承Component
import Component from 'react'
export default class page1 extends Component{
constructor(){
this.state={a:''}
}
}
Component源码里面,setState执行原理,
Component.prototype.setState = function (partialState, callback) {
if (
typeof partialState !== 'object' &&
typeof partialState !== 'function' &&
partialState != null
) {
throw new Error(
'setState(...): takes an object of state variables to update or a ' +
'function which returns an object of state variables.',
);
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
Component类组件构造函数
function Component(props, context, updater) {
this.props = props;
this.context = context;
// If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
2、jsx被编译为createElement结构,那createElement源码是如何创建虚拟DOM对象的
ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
3、creatRef源码为什么要在current里面取
export function createRef(): RefObject {
const refObject = {
current: null,
};
if (__DEV__) {
Object.seal(refObject);
}
return refObject;
}