zoukankan      html  css  js  c++  java
  • Typechecking With PropTypes

    Note: React.PropTypes is deprecated as of React v15.5. Please use the prop-types library instead.

    As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like Flow or TypeScript to typecheck your whole application. But even if you don't use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special propTypesproperty:

    import PropTypes from 'prop-types';
    
    class Greeting extends React.Component {
      render() {
        return (
          <h1>Hello, {this.props.name}</h1>
        );
      }
    }
    
    Greeting.propTypes = {
      name: PropTypes.string
    };

    PropTypes exports a range of validators that can be used to make sure the data you receive is valid. In this example, we're using PropTypes.string. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, propTypes is only checked in development mode.

    1.将父组件参数全部传递给子组件的快捷方法:

    {...this.props}

    2.设置默认prop值

    step-1  使用ES6语法定义变量defaultProps

    const defaultProps={
           username:'sunny'    //当父组件没有设置对应参数时,会显示该内容,若设置了,设置参数会覆盖自定义默认参数
    }

    step-2  为所在组件的参数设置默认值

    BodyIndex.defaultProps=defaultProps    

    PS:含props的属性,获取或传递的,都是来自父组件的参数值

    Default Prop Values--》defaultProps属性

    You can define default values for your props by assigning to the special defaultProps property:

    class Greeting extends React.Component {
      render() {
        return (
          <h1>Hello, {this.props.name}</h1>
        );
      }
    }
    
    // Specifies the default values for props:
    Greeting.defaultProps = {
      name: 'Stranger'
    };
    
    // Renders "Hello, Stranger":
    ReactDOM.render(
      <Greeting />,
      document.getElementById('example')
    );

    The defaultProps will be used to ensure that this.props.name will have a value if it was not specified by the parent component. The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.

  • 相关阅读:
    strong,weak, retain, assign的区别@property的参数
    iOS 声明属性关键字讲解
    iOS中ARC和非ARC混用
    存储过程修改产品描述页图片alt描述信息
    mysql字符串函数(转载)
    读者证
    存储过程
    复制档案或目录 linux cp命令详解
    linux shell获取时间
    linux 备份日志文件
  • 原文地址:https://www.cnblogs.com/jeanneze/p/6856539.html
Copyright © 2011-2022 走看看