In Typescript, React components can be defined as functions (react.fc <>) or classes (inherited from react.ponent).
React.FC (Function component)
React.FC is a functional component that is a generic type used in TypeScript. FC is short for FunctionComponent. React.FC can be written as React.functionComponent.
When using React.FC to write React components, do not use setState. Instead, use Hook apis such as useState(), useEffect, etc. Function components are also called stateless components.
React.fc includes the generic PropsWithChildren without explicitly declaring the type of props. Children. React.fc <> is explicit for return types, whereas the normal function version is implicit (otherwise additional comments are required).
React.fc provides static properties for type checking and autocompletion: displayName, propTypes, and defaultProps (note: defaultProps can be a bit of a problem when used with React.fc).
import React, { useState } from 'react';
interfaceIProps { test? :any;
}
const Index: React.FC<IProps> = (props) = > {
let [count, setCount] = useState(0);
return(
<div>
<p>{count}</p>
<button onClick={()= > setCount(count + 1)}>Click</button>
</div>
);
};
export default Index;
Copy the code
React.ponent (class component)
React.ponent is in ES6 form, replacing the react.createclass component defined in ES5 native way.
To define a class component, you need to inherit from React.ponent. React.ponent is a class component. In TypeScript, react.ponent is a generic type (aka react.ponent
import React, {Component} from 'react';
interfaceIProps { message1? :any
}
interface IState {
message2:any
}
class Index extends Component<IProps.IState> {
// The constructor
constructor(props: IProps, context: any) {
super(props, context);
this.state={
message2:"test"}}render() {
return (
<div>
<div>{this.state.message2}</div>
<div>{this.props.message1}</div>
</div>); }}export default Index;
Copy the code
The difference between function components and class components
The most obvious difference is that syntactically, the function component is a pure function that takes a props object and returns a react element. The class component needs to inherit from React.componentand create the render function that returns the React element, which takes more code, even though they achieve the same effect.
Class components are instantiated when used, while function components simply execute the function and return the result.
Function components cannot access this object. They cannot access lifecycle methods. There is no state.
Class components have this, life cycle, and state.
Stateless (function) components can only access the input props. The same props will render the same result, with no side effects.
Function components perform better than class components. If you don’t know what component type to use, React.FC is recommended.