2016-08-23 160 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

相关问题