Javascript 功能无状态组件中的 PropTypes
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44582209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PropTypes in functional stateless component
提问by Alan Jenshen
Without using class, how do I use PropTypes in functional stateless component of react?
在不使用类的情况下,如何在 react 的功能性无状态组件中使用 PropTypes?
export const Header = (props) => (
<div>hi</div>
)
回答by Michael
The official docsshow how to do this with ES6 component classes, but the same applies for stateless functional components.
在官方的文档显示如何使用ES6组件类做到这一点,但同样适用于无状态的功能组件。
Firstly, npm install/ yarn addthe new prop-types packageif you haven't already.
首先,npm install/yarn add在新的道具类型包装,如果你还没有准备好。
Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.
然后,在定义无状态功能组件之后,在导出它之前添加您的 propTypes(如果需要,也可以添加 defaultProps)。
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;
回答by I Putu Yoga Permana
It isn't different with the stateful, You can add it like:
它与 stateful 没有什么不同,您可以添加它:
import?PropTypes?from?'prop-types';
Header.propTypes = {
title: PropTypes.string
}
Here is a link to prop-typesnpm
这是prop-typesnpm的链接
回答by lokeshj
Same way you do in class based components:
与您在基于类的组件中所做的相同:
import PropTypes from 'prop-types';
const funcName = (props) => {
...
}
funcName.propTypes = {
propName: PropTypes.string.isRequired
}
Note: You might have to install prop-typesvia npm install prop-typesor yarn add prop-types, depending on the React version you are using.
注意:您可能必须prop-types通过npm install prop-types或安装yarn add prop-types,具体取决于您使用的 React 版本。
回答by Ashutosh Tiwari
It's done the same way you do with Class Based Components
它的完成方式与基于类的组件相同
import PropTypes from "prop-types";
const = function_name => {}
function_name.propTypes = {
prop_name : PropTypes.number
. . . . . . . . . . . . . .
}
Hope This Helps !
希望这可以帮助 !

