PropTypes in functional stateless component

被刻印的时光 ゝ 提交于 2019-11-28 21:49:28

问题


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

export const Header = (props) => (
   <div>hi</div>
)

回答1:


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 }) => <div>hi {name}</div>;

Header.propTypes = {
  name: PropTypes.string
};

// Same approach for defaultProps too
Header.defaultProps = {
  name: "Alan"
};

export default Header;



回答2:


It isn't different with the stateful, You can add it like:

import PropTypes from 'prop-types';
Header.propTypes = {
  title: PropTypes.string
}

Here is a link to prop-types npm



来源:https://stackoverflow.com/questions/44582209/proptypes-in-functional-stateless-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!