本文介绍了功能性无状态组件中的PropTypes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不使用类的情况下,如何在React的功能性无状态组件中使用PropTypes?

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

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

推荐答案

官方文档展示了如何使用ES6组件类来实现这一点,但同样适用于无状态功能组件.

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

首先, npm install / yarn add prop-types 包(如果您还没有的话).

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

然后,在定义无状态功能组件之后,在导出之前,添加您的 propTypes (如果需要,还添加 defaultProps ).

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;

这篇关于功能性无状态组件中的PropTypes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:45