资讯专栏INFORMATION COLUMN

React手稿之类型检查

tomorrowwu / 3452人阅读

摘要:类型检查是为了确保传入组件的参数正确性。通常在项目中可以使用或者来实现。示例以上内容在实现一个通用组件时非常有用。类型检查和参数默认值一起使用,保证组件的正常运行。

Typechecking With PropTypes

类型检查是为了确保传入组件的参数正确性。

通常在项目中可以使用Flow或者TypeScript来实现。

React提供了PropTypes来检查类型。

示例:

</>复制代码

  1. import PropTypes from "prop-types";
  2. class Greeting extends React.Component {
  3. render() {
  4. return (
  5. Hello, {this.props.name}

  6. );
  7. }
  8. }
  9. Greeting.propTypes = {
  10. name: PropTypes.string
  11. };
PropTypes

</>复制代码

  1. import PropTypes from "prop-types";
  2. MyComponent.propTypes = {
  3. // You can declare that a prop is a specific JS type. By default, these
  4. // are all optional.
  5. optionalArray: PropTypes.array,
  6. optionalBool: PropTypes.bool,
  7. optionalFunc: PropTypes.func,
  8. optionalNumber: PropTypes.number,
  9. optionalObject: PropTypes.object,
  10. optionalString: PropTypes.string,
  11. optionalSymbol: PropTypes.symbol,
  12. // Anything that can be rendered: numbers, strings, elements or an array
  13. // (or fragment) containing these types.
  14. optionalNode: PropTypes.node,
  15. // A React element.
  16. optionalElement: PropTypes.element,
  17. // You can also declare that a prop is an instance of a class. This uses
  18. // JS"s instanceof operator.
  19. optionalMessage: PropTypes.instanceOf(Message),
  20. // You can ensure that your prop is limited to specific values by treating
  21. // it as an enum.
  22. optionalEnum: PropTypes.oneOf(["News", "Photos"]),
  23. // An object that could be one of many types
  24. optionalUnion: PropTypes.oneOfType([
  25. PropTypes.string,
  26. PropTypes.number,
  27. PropTypes.instanceOf(Message)
  28. ]),
  29. // An array of a certain type
  30. optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
  31. // An object with property values of a certain type
  32. optionalObjectOf: PropTypes.objectOf(PropTypes.number),
  33. // An object taking on a particular shape
  34. optionalObjectWithShape: PropTypes.shape({
  35. color: PropTypes.string,
  36. fontSize: PropTypes.number
  37. }),
  38. // You can chain any of the above with `isRequired` to make sure a warning
  39. // is shown if the prop isn"t provided.
  40. requiredFunc: PropTypes.func.isRequired,
  41. // A value of any data type
  42. requiredAny: PropTypes.any.isRequired,
  43. // You can also specify a custom validator. It should return an Error
  44. // object if the validation fails. Don"t `console.warn` or throw, as this
  45. // won"t work inside `oneOfType`.
  46. customProp: function(props, propName, componentName) {
  47. if (!/matchme/.test(props[propName])) {
  48. return new Error(
  49. "Invalid prop `" + propName + "` supplied to" +
  50. " `" + componentName + "`. Validation failed."
  51. );
  52. }
  53. },
  54. // You can also supply a custom validator to `arrayOf` and `objectOf`.
  55. // It should return an Error object if the validation fails. The validator
  56. // will be called for each key in the array or object. The first two
  57. // arguments of the validator are the array or object itself, and the
  58. // current item"s key.
  59. customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
  60. if (!/matchme/.test(propValue[key])) {
  61. return new Error(
  62. "Invalid prop `" + propFullName + "` supplied to" +
  63. " `" + componentName + "`. Validation failed."
  64. );
  65. }
  66. })
  67. };
Requiring Single Child

</>复制代码

  1. import PropTypes from "prop-types";
  2. class MyComponent extends React.Component {
  3. render() {
  4. // This must be exactly one element or it will warn.
  5. const children = this.props.children;
  6. return (
  7. {children}
  8. );
  9. }
  10. }
  11. MyComponent.propTypes = {
  12. children: PropTypes.element.isRequired
  13. };
Default Prop Values

</>复制代码

  1. class Greeting extends React.Component {
  2. render() {
  3. return (
  4. Hello, {this.props.name}

  5. );
  6. }
  7. }
  8. // Specifies the default values for props:
  9. Greeting.defaultProps = {
  10. name: "Stranger"
  11. };
  12. // Renders "Hello, Stranger":
  13. ReactDOM.render(
  14. ,
  15. document.getElementById("example")
  16. );

以上内容在实现一个通用React组件时非常有用。类型检查和参数默认值一起使用,保证组件的正常运行。

推荐阅读《React 手稿》

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/108633.html

相关文章

  • React手稿State Hooks of Hooks

    摘要:官方也陈述,接下来的的工作会投入到中。从目前官方的文档可以看出,从以下四个方面来提高的编码。生命周期自定义方法的主要用途是替代之前版本的组件。说明到目前为止,在已发布的版本中有该功能,想体验该功能,必须安装。 React Hooks React在16.7.0-alpha.0版本中提到了Hooks的概念,目前还是Proposal阶段。 官方也陈述,接下来的90%的工作会投入到React ...

    DC_er 评论0 收藏0
  • React手稿 React-Redux

    摘要:属性是必须的。需要一个与的一致。必须在的返回原。调试插件日志安装组件。然后加入到中即可例如扩展程序需要在应用市场安装然后在中使用增强功能将加入即可在线实例推荐阅读手稿 React-Redux Redux Action function addTodo(text) { return { type: ADD_TODO, text } } type 属性是必须的。...

    Freelander 评论0 收藏0
  • React手稿 React-Saga

    摘要:相当于一个放置在与中的垫片。之所以称之谓副作用呢,就是为了不让触发一个时,立即执行。也就是在与之间做一个事情,比如异步获取数据等。使用了中的功能,避免了像的回调地狱。把放入中最后再实现相就的即可在线示例推荐阅读手稿 Redux-Saga redux-saga 是一个用于管理应用程序副作用(例如异步获取数据,访问浏览器缓存等)的javascript库,它的目标是让副作用管理更容易,执行更...

    notebin 评论0 收藏0
  • React手稿高阶组件

    摘要:示例使用场景代码复用类似版本之前的。多个组件同用一段代码,或者同样的方法时,可以使用。示例在线示例抽象和更改可以通过包裹的组件公共抽象出来。可以通过包裹的组件传递修改添加等的示例渲然劫持条件渲然。示例反向继承返回的高阶组件类继承了。 Higher-Order Components HOC 不是React的标准API。 HOC 是一个函数。 HOC 返回一个Component。 示例...

    dkzwm 评论0 收藏0
  • React手稿 - Context

    摘要:提供了除之外的传参数的方式。是全局跨组件传递数据的。在线示例推荐阅读手稿 Context Context提供了除props之外的传参数的方式。 Context是全局跨组件传递数据的。 API React.createContext const {Provider, Consumer} = React.createContext(defaultValue); Provider ...

    qingshanli1988 评论0 收藏0

发表评论

0条评论

tomorrowwu

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<