美文网首页
React官网学习实践 - 使用PropTypes检查类型

React官网学习实践 - 使用PropTypes检查类型

作者: 张中华 | 来源:发表于2018-11-20 22:08 被阅读14次

随着应用日渐庞大,你可以通过类型检查捕获大量错误。 对于某些应用来说,你还可以使用 FlowTypeScript 这样的 JavsScript 扩展来对整个应用程序进行类型检查。然而即使你不用它们,React 也有一些内置的类型检查功能。要检查组件的属性,你需要配置特殊的 propTypes 属性.

npm install prop-types
PropTypes 包含一整套验证器,可用于确保你接收的数据是有效的。在这个示例中,我们使用了 PropTypes.string。当你给属性传递了无效值时,JavsScript 控制台将会打印警告。出于性能原因,propTypes 只在开发模式下进行检查。

虽然在控制台报错,但是在界面还是可以正常显示。



code:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
                <Greeting name="hello"/>
                <Greeting name={parseInt(1)}/>
            </div>
        );
    }
}
class Greeting extends Component {
    render() {
        return (
            <h1>Hello, {this.props.name}</h1>
        );
    }
}
Greeting.propTypes = {
    name: PropTypes.string
};
export default App;

限制单个子代

import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  render() {
    // This must be exactly one element or it will warn.
    const children = this.props.children;
    return (
      <div>
        {children}
      </div>
    );
  }
}

MyComponent.propTypes = {
  children: PropTypes.element.isRequired
};

属性默认值

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// 为属性指定默认值:
Greeting.defaultProps = {
  name: 'Stranger'
};

defaultProps 用来确保 this.props.name 在父组件没有特别指定的情况下,有一个初始值。类型检查发生在 defaultProps 赋值之后,所以类型检查也会应用在 defaultProps 上面。

相关文章

网友评论

      本文标题:React官网学习实践 - 使用PropTypes检查类型

      本文链接:https://www.haomeiwen.com/subject/tguzfqtx.html