问题
如何区分函数组件和类组件?
答案
可以使用instanceof 或者Component.prototype.isReactComponent。
示例
函数组件
export default function FunctionComonent() {if(FunctionComonent.prototype.isReactComponent){console.log('FunctionComonent是类组件')}else{console.log('FunctionComonent函数式组件')}return <div>这是函数组件</div>
}
类组件
import React from 'react';export default class ClassComponent extends React.Component {constructor(props) {super();if(ClassComponent.prototype.isReactComponent){console.log('ClassComponent 是类组件')}else{console.log('ClassComponent函数式组件')}}render() { return (<div>这是一个Class组件</div>) }
}
引用
import React from 'react';
import ReactDOM from 'react-dom';
import ClassComponent from './compareFunctionComponentAndClassComponent/ClassComponent.jsx';
import FunctionComponent from './compareFunctionComponentAndClassComponent/FunctionComponent';const clas = new ClassComponent();
console.log(`ClassComponent is Class ${clas instanceof React.Component}`);const func = new FunctionComponent();
console.log(`FunctionComponent is Class ${func instanceof React.Component}`);ReactDOM.render(<React.StrictMode><ClassComponent /><FunctionComponent /></React.StrictMode>,document.getElementById('root')
);
结果