【问题标题】:undefined props best practices未定义的道具最佳实践
【发布时间】:2017-12-25 14:02:52
【问题描述】:

让我们假设有一个Child 组件正在以这种方式呈现

<Child text="foo" action={this.bar} />

这里的textaction 是给子组件的两个道具。

但是如果没有提供给Child 组件的道具

<Child />

Child 组件会引发 undefined 道具异常 this.props.text is undefined 或类似的东西。

即使没有提供任何道具,渲染Child 组件的最佳实践是什么?

我是否必须在Child 组件中总是这样检查。

if (this.props.text !== undefined) && (this.props.action !== undefined) 
  //then render

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    最佳做法是使用PropTypes 包,例如:

    import React, { Component } from 'react'
    import PropTypes from 'prop-types'
    
    class Person extends Component {
      render () {
        <h1>{this.props.name}</h1>
      }
    }
    
    Person.propTyeps = {
      name: PropTypes.string.isRequired
    }
    

    这将在控制台中显示一条警告消息。

    要使用它,您需要安装它:

    $ npm install --save prop-types
    

    您可以找到更多文档here,希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2011-03-28
      相关资源
      最近更新 更多