How to set component default props on React component

后端 未结 9 911
孤街浪徒
孤街浪徒 2020-12-07 13:52

I use the code below to set default props on a React component but it doesn\'t work. In the render() method, I can see the output \"undefined props\" was printe

9条回答
  •  佛祖请我去吃肉
    2020-12-07 14:06

    For those using something like babel stage-2 or transform-class-properties:

    import React, { PropTypes, Component } from 'react';
    
    export default class ExampleComponent extends Component {
       static contextTypes = {
          // some context types
       };
    
       static propTypes = {
          prop1: PropTypes.object
       };
    
       static defaultProps = {
          prop1: { foobar: 'foobar' }
       };
    
       ...
    
    }
    

    Update

    As of React v15.5, PropTypes was moved out of the main React Package (link):

    import PropTypes from 'prop-types';
    

    Edit

    As pointed out by @johndodo, static class properties are actually not a part of the ES7 spec, but rather are currently only supported by babel. Updated to reflect that.

提交回复
热议问题