2016-08-23 154 views
2

我正在查看DatePickerIOS組件的文檔,他們使用getDefaultProps()來初始化組件中的道具。在React Native中使用ES6的getDefaultProps函數等效於什麼?

getDefaultProps: function() { 
    return { 
     date: new Date(), 
     timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset()/60, 
    }; 
    }, 

    getInitialState: function() { 
    return { 
     date: this.props.date, 
     timeZoneOffsetInHours: this.props.timeZoneOffsetInHours, 
    }; 
    }, 

什麼是使用ES6語法的等價物?因爲我一直在使用:

constructor(props) { 
    super(props); 

    this.state = { 
    //equivalent to getInitialState is here 
    }; 
} 

我應該做這個.props = {}來設置我的默認道具嗎?

+1

如果有幫助,請標記爲正確答案。 –

回答

7

看到這個:

https://github.com/facebook/react/issues/3725

class X extends React.Component { 
} 
X.defaultProps = {...} 

如果您使用的是巴貝爾,插件變換級的屬性包,你可以這樣做:

class X extends React.Component { 
    static defaultProps = {...} 
} 
+3

爲什麼downvote? –

1
class Video extends React.Component { 
    static defaultProps = { 
    autoPlay: false, 
    maxLoops: 10, 
    } 
    static propTypes = { 
    autoPlay: React.PropTypes.bool.isRequired, 
    maxLoops: React.PropTypes.number.isRequired, 
    posterFrameSrc: React.PropTypes.string.isRequired, 
    videoSrc: React.PropTypes.string.isRequired, 
    } 
    state = { 
    loopsRemaining: this.props.maxLoops, 
    } 
} 

https://babeljs.io/blog/2015/06/07/react-on-es6-plus

相關問題