PropTypes in functional stateless component

前端 未结 5 664
情深已故
情深已故 2020-12-24 04:01

Without using class, how do I use PropTypes in functional stateless component of react?

export const Header = (props) => (
   
hi
)
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 04:40

    The official docs show how to do this with ES6 component classes, but the same applies for stateless functional components.

    Firstly, npm install / yarn add the new prop-types package if you haven't already.

    Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.

    import React from "react";
    import PropTypes from "prop-types";
    
    const Header = ({ name }) => 
    hi {name}
    ; Header.propTypes = { name: PropTypes.string }; // Same approach for defaultProps too Header.defaultProps = { name: "Alan" }; export default Header;

提交回复
热议问题