• 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.

  • 相关阅读:
    Shell高级编程学习笔记(基础篇)
    基于Python的机器学习实战:Apriori
    基于Python的机器学习实战:AadBoost
    Theano教程:Python的内存管理
    基于theano的降噪自动编码器(Denoising Autoencoders--DA)
    基于theano的深度卷积神经网络
    推荐系统之矩阵分解及C++实现
    推荐系统之协同过滤的原理及C++实现
    一步一步详解ID3和C4.5的C++实现
    Principal components analysis(PCA):主元分析
  • 原文地址:https://www.cnblogs.com/jeanneze/p/6856539.html
Copyright © 2020-2023  润新知