Talking about the use of React. FC and React. Component of React

  • 2021-11-13 06:42:16
  • OfStack

Directory 1. React. FC < >
2. class xx extends React.Component

Components of React can be defined as functions (React. FC < > ) or class (inherited from React. Component).

1. React.FC < >

1. React. FC is a functional component, a generic used in TypeScript, FC is the abbreviation of FunctionComponent, and in fact React. FC can be written as React. FunctionComponent:


const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
  <div>{message}</div>
);

2. React. FC contains generics for PropsWithChildren without explicitly declaring the type for props. children. React. FC < > It is explicit for return types, while the normal function version is implicit (otherwise, additional comments are required).

3. React. FC provides static properties for type checking and auto-completion: displayName, propTypes, and defaultProps (Note: defaultProps in combination with React. FC has a few problems).

4. When we use React. FC to write React components, we can't use setState. Instead, we use useState (), useEffect and other Hook API.

Examples (demonstrated here using Ali's Ant Desgin Pro framework):


const SampleModel: React.FC<{}> = () =>{   //React.FC<> For typescript Generics used 
   const [createModalVisible, handleModalVisible] = useState<boolean>(false); 
   return{
   {/**  Trigger mode box **/}
   <Button style={{fontSize:'25px'}}  onClick={()=>handleModalVisible(true)} > Sample </Button>
   {/**  Modal frame assembly **/}
   <Model onCancel={() => handleModalVisible(false)} ModalVisible={createModalVisible} /> 
  }

2. class xx extends React.Component

To define an class component, you need to inherit React. Component. React. Component is a class component, and in TypeScript, React. Component is a common type (aka ES90Component < PropType, StateType > ), so provide it with (optional) prop and state type parameters:

Examples (demonstrated here using Ali's Ant Desgin Pro framework):


class SampleModel extends React.Component {
  state = {
    createModalVisible:false,
  };

  handleModalVisible =(cVisible:boolean)=>{
    this.setState({createModalVisible:cVisible});
  };
  return {
  {/**  Trigger mode box **/}
   <Button onClick={()=>this.handleModalVisible(true)} > Sample </Button>
   {/**  Modal frame assembly **/}
   <Model onCancel={() => handleModalVisible(false)} ModalVisible={this.state.createModalVisible} /> 
  }

ps: Simply put, when you don't know what component type to use, use React. FC.


Related articles: