React如何判断是函数组件还是类组件
- 方法一: 通过instancOf
lass A {}
class B extends A {}
console.log(B.prototype instanceof A); // true
而我们的类组件写法,是通过继承React.Component来,所以可以通过instanceOf来判断
class Child extends React.Component {
render() {
return <p>hi</p>;
}
}
Child.prototype instanceOf React.Component // true
上面为true说明是类组件,上面等价于,即原型链的继承
Child.prototype.__proto__ === React.Component.prototype
实际上React没有用这种办法,而是直接通过添加标记的方式
- React实际方法,判断函数组件还是类组件?
class Component {}
Component.isReactClass = {};
class Greeting extends Component {}
console.log(Greeting.isReactClass); //
// 上面方法存在静态属性丢失,所以添加到prototype上
class Component {}
Component.prototype.isReactComponent = {};
class Greeting extends Component {}
if(Greeting.prototype.isReactComponent){
console.log('是类组件')
}else{
console.log('函数式组件')
}
为什么要判断是类组件还是函数是组件?
因为函数组件和类组件调用方式不一样
- 函数组件
// your code
const Child = (props) => {
return <p>Hello</p>;
}
// Inside React
const result = Greeting(props); // <p>Hello</p>
函数组件没有this,所以不许要实例化
- 类组件
// Your code
class Child extends React.Component {
render() {
return <p>Hello</p>;
}
}
// Inside React
const instance = new Greeting(props); // Greeting {}
const result = instance.render(); // <p>Hello</p>
类组件有this所以必须通过实例化来调用
- 类定义必须用new调用
function Person(name) {
this.name = name;
console.log(1);
}
Person.prototype.sayHi = function() {
console.log('hi');
}
Person('age') // 1
Person.sayHi() // 报错
new Person().sayHi() // hi
class Person{
age = 11
sayHi(){
console.log('hi');
}
static staticSay(){
console.log('static hi');
console.log(this.age);
}
sayAage(){
console.log(this.age);
}
}
Person() //报错,类必须实实例化后才使用
Person.staticSay() // static hi
new Person().sayHi() // hi
new Person().sayAage() // 11
class Person{
age = 1
sayHi(){
console.log('hi');
}
static staticSay(){
console.log('static hi');
//报错,因为这里this指类Person而不是实例,类还不支持静态属性
// console.log(this.age); //报错
console.log(this.log()); //可以
}
static log(){
console.log('log');
}
}
new Person().sayAage() // 1
Person.staticSay()
- 回忆new的作用
function myNew(fn,args){
var obj = {}
obj.__proto__ = fn.prototype
//创建实例的时候传参
var res = fn.apply(obj,args)
//当构造函数有return时,返回return值,没有则返回obj{}
return res instanceof Object ? res : obj
}